Php 类反射:缺少属性
我试图使用反射获取类的所有属性,但有些属性仍然混乱 下面是我的代码中发生的一个小示例Php 类反射:缺少属性,php,reflection,properties,Php,Reflection,Properties,我试图使用反射获取类的所有属性,但有些属性仍然混乱 下面是我的代码中发生的一个小示例 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; // Gi
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)
Property [ public $a ]
Property [ protected $b ]
Property [ private $c ]
第二个解决方案是什么
$reflection = new ReflectionClass($test);
$properties = $reflection->getProperties(ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PRIVATE | ReflectionProperty::IS_PROTECTED);
foreach($properties as $property) {
echo $property->__toString()."<br>";
}
在第一种情况下,缺少私有属性,在第二种情况下,缺少“实例化后”属性 不知道如何才能获得所有属性?
(最好使用反射,因为我还想知道属性是公共的还是私有的…如果还需要列出动态创建的对象属性,请使用
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
OP还需要在对象实例化之后设置的属性。这就是我想要的。谢谢不客气。还感谢@AmalMurali的演示:)@hek2mgl:+1。这会奏效的。我已将答案更新为使用
getName()
而不是$p->name
。我还更改了变量名,以便OP更容易理解。@hek2mgl:顺便说一句,编辑后,同一句话在答案中重复了两次。在输出部分之前,我已经包含了这一点,但您似乎没有注意到;)