【问题标题】:iterate only through existing objects properties, not them from parent class?仅遍历现有对象的属性,而不是来自父类的?
【发布时间】:2010-04-12 06:36:33
【问题描述】:

我有一个类可以扩展另一个类。

当我迭代当前对象时,我会获得所有属性,甚至是超类中的属性。

我只想遍历当前对象。我该怎么做?

foreach($this as $key => $value) {
    echo $key . ': ' . $value;
}

【问题讨论】:

    标签: php oop


    【解决方案1】:

    非常有趣的问题。

    我强烈建议您阅读此处的示例 - http://dsl093-056-122.blt1.dsl.speakeasy.net/edu/oreilly/Oreilly_Web_Programming_bookshelf/webprog/php/ch06_05.htm 它们将使您对内省有更深入的了解。关于这些方法的参考在这里 - http://www.php.net/manual/en/ref.classobj.php


    这是带有测试用例的函数。它只能在 PHP 5+ 中工作,因为它使用了在此之前不可用的反射。您可以在此处阅读有关反射的更多信息 - http://www.php.net/manual/en/class.reflectionclass.php

    <?php
    
    echo '<pre>';
    
    class A {
        public $pub_a = 'public a';
        private $priv_a = 'private a';
    }
    
    class B extends A {
        public $pub_b = 'public b';
        private $priv_b = 'private b';
    }
    
    $b = new B();
    
    print_r(getChildrenProperties($b));
    
    function getChildrenProperties($object) {
        $reflection = new ReflectionClass(get_class($object));
        $properties = array();
    
        foreach ($reflection->getProperties() as $k=>$v) {
            if ($v->class == get_class($object)) {
                $properties[] = $v;
            }
        }
    
        return $properties;
    }
    

    【讨论】:

    • 一个小技巧,但代码有效。感谢您深入了解它!
    【解决方案2】:

    您也可以尝试使用 PHP 反射 http://php.net/manual/en/book.reflection.php

    我猜你可以使用@Ivo Sabev 回答是:

     $properties = get_class_vars(ChildClass);
     $bproperties = get_class_vars(ParentClass);
    

    现在遍历所有未出现在 $bproperties 中的 $properties。

    【讨论】:

    • 是的,就是这个想法,但这些函数实际上并没有给你私有属性。我不是在看 ReflectionClass,可能会写一个小函数来解决这个问题。
    【解决方案3】:

    get_class_vars 手册页在用户 cmets 部分(最顶部)中包含了执行此操作的示例。

    http://us.php.net/manual/en/function.get-class-vars.php

    【讨论】:

    • 但那只得到类变量,而不是我猜的对象变量?
    猜你喜欢
    • 2021-11-27
    • 1970-01-01
    • 2012-01-08
    • 2014-08-09
    • 1970-01-01
    • 2011-04-23
    • 2016-05-12
    相关资源
    最近更新 更多