我无法通过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
有什么想法吗?
答案 0 :(得分:7)
ReflectionClass::getProperties()
仅获取类显式定义的属性。要反映您在对象上设置的所有属性,请使用继承自ReflectionClass
的{{3}}并在运行时实例上运行:
$reflect = new ReflectionObject($this);
或ReflectionObject
,忘记反思,只需使用Tim Cooper says。
答案 1 :(得分:3)
在这种情况下,您无法使用ReflectionClass
。将$props
变量替换为以下内容以使其正常工作:
$props = get_object_vars($this);
如果没有其他方法需要从ReflectionObject
致电(请参阅BoltClock's answer),那么这是最简单的解决方案。
答案 2 :(得分:1)
class Foo { }
$foo = new Foo();
$foo->a = "a";
$foo->b = "b";
echo Reflection::export(new ReflectionObject($foo));
// Object of class [ <user> class Foo ] {
// @@ /var/www/files/r.php 2-2
// - Constants [0] {
// }
// - Static properties [0] {
// }
// - Static methods [0] {
// }
// - Properties [0] {
// }
// - Dynamic properties [2] {
// Property [ <dynamic> public $a ]
// Property [ <dynamic> public $b ]
// }
// - Methods [0] {
// }
// }
答案 3 :(得分:0)
给出一个匿名类的实例
$object = new class()
{
private $fooPrivate = 'barPrivate';
public $fooPublic = 'barPublic';
public static $fooStaticPublic = 'barStaticPublic';
public function getProperties(): array
{
return get_object_vars( $this );
}
};
$object->fooDynamic = 'barDynamic';
ReflectionClass
/** lists: `fooPrivate`, `fooPublic`, `fooStaticPublic` */
var_export(
( new ReflectionClass( $object ) )
->getProperties()
);
/** lists: `fooPublic`, `fooStaticPublic` */
var_export(
( new ReflectionClass( $object ) )
->getProperties( ReflectionProperty::IS_PUBLIC )
);
ReflectionObject
/** lists: `fooPrivate`, `fooPublic`, `fooStaticPublic`, `fooDynamic` */
var_export(
( new ReflectionObject( $object ) )
->getProperties()
);
/** lists: `fooPublic`, `fooStaticPublic`, `fooDynamic` */
var_export(
( new ReflectionObject( $object ) )
->getProperties( ReflectionProperty::IS_PUBLIC )
);
get_object_vars()
/** lists: `fooPublic`, `fooDynamic` */
var_export(
get_object_vars( $object )
);
/** lists: `fooPrivate`, `fooPublic`, `fooDynamic` */
var_export(
$object->getProperties()
);
ReflectionClass::getProperties()
ReflectionObject::getProperties()
ReflectionClass::getProperties()
和ReflectionObject::getProperties()
都
get_object_vars()