【问题标题】:Class Reflection : Missing Properties类反射:缺少属性
【发布时间】:2014-05-24 15:41:44
【问题描述】:

我正在尝试使用反射获取类的所有属性,但有些属性仍然混乱。

这里是我的代码中发生的事情的一个小例子

Class Test {
    public $a = 'a';
    protected $b = 'b';
    private $c = 'c';
}

$test = new Test();
$test->foo = "bar";

所以此时我的 $test 对象有 4 个属性(a、b、c 和 foo)。
foo 属性被视为公共属性,因为我可以这样做

echo $test->foo; // Gives : bar

相反,b 或 c 被视为私有属性

echo $test->b; // Gives : Cannot access protected property Test::$b
echo $test->c; // Gives : Cannot access private property Test::$c

 


我尝试了两种解决方案来获取我的 $test 对象的所有属性(a、b、c 和 foo)

第一个

var_dump(get_object_vars($test));

这给了

array (size=2)
    'a' => string 'a' (length=1)
    'foo' => string 'bar' (length=3)

 
第二个解决方案

$reflection = new ReflectionClass($test);
$properties = $reflection->getProperties(ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PRIVATE | ReflectionProperty::IS_PROTECTED);
foreach($properties as $property) {
    echo $property->__toString()."<br>";
}

这给了

Property [ public $a ]
Property [ protected $b ]
Property [ private $c ]

 
在第一种情况下,私有属性丢失,在第二种情况下,“实例化后”属性丢失。

不知道如何才能获得所有属性?
(最好用反射,因为我也想知道一个属性是公共的,私有的......)

【问题讨论】:

    标签: php reflection properties


    【解决方案1】:

    如果您还需要列出动态创建的对象属性,请使用ReflectionObject 而不是ReflectionClass:

    $test = new Test();
    $test->foo = "bar";
    
    $class = new ReflectionObject($test);
    foreach($class->getProperties() as $p) {
        $p->setAccessible(true);
        echo $p->getName() . ' => ' . $p->getValue($test) . PHP_EOL;
    }
    

    请注意,我使用ReflectionProperty::setAccessible(true) 来访问protected 或private 属性的值。

    输出:

    a => a
    b => b
    c => c
    foo => bar
    

    Demo

    【讨论】:

    • OP 还想要在对象实例化之后设置的属性。
    • 这就是我想要的。谢谢!
    • 不客气。还要感谢 @AmalMurali 的演示 :)
    • @hek2mgl:+1。这会奏效。我已将答案更新为使用getName() 而不是$p-&gt;name。我还更改了变量名称,以便 OP 更容易理解它。
    • @hek2mgl:顺便说一句,在您编辑之后,您现在的答案中重复了两次相同的句子。我已经在 Output 部分之前包含了那个,但您似乎错过了;)
    猜你喜欢
    • 1970-01-01
    • 2018-11-16
    • 1970-01-01
    • 2016-01-09
    • 1970-01-01
    • 1970-01-01
    • 2021-12-20
    • 1970-01-01
    • 2020-09-09
    相关资源
    最近更新 更多