我没能通过PHP的反射得到动态实例变量
示例代码:
<?php
class Foo
{
public function bar()
{
$reflect = new ReflectionClass($this);
$props = $reflect->getProperties();
var_export($props);
die;
}
}
$foo = new Foo();
$foo->a = "a";
$foo->b = "b";
$foo->bar(); // Failed to print out variable a and b
Run Code Online (Sandbox Code Playgroud)
任何的想法?
ReflectionClass::getProperties()只获取由类明确定义的属性.要反映您在对象上设置的所有属性,请使用ReflectionObject继承自ReflectionClass运行时实例的属性并对其进行操作:
$reflect = new ReflectionObject($this);
Run Code Online (Sandbox Code Playgroud)
或者正如蒂姆库珀所说,忘记反思,而只是使用get_object_vars().