【发布时间】: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