30

它似乎不起作用:

$ref = new ReflectionObject($obj);

if($ref->hasProperty('privateProperty')){
  print_r($ref->getProperty('privateProperty'));
}

它进入 IF 循环,然后抛出错误:

属性 privateProperty 不存在

:|

$ref = new ReflectionProperty($obj, 'privateProperty')也不行……

文档页面列出了一些常量,包括IS_PRIVATE. 如果我无法访问私有财产大声笑,我怎么能使用它?

4

4 回答 4

60
class A
{
    private $b = 'c';
}

$obj = new A();

$r = new ReflectionObject($obj);
$p = $r->getProperty('b');
$p->setAccessible(true); // <--- you set the property to public before you read the value

var_dump($p->getValue($obj));
于 2012-07-22T23:54:44.057 回答
2

请注意,如果您需要获取来自父类的私有属性的值,则接受的答案将不起作用。

为此,您可以依赖Reflection API 的 getParentClass 方法

另外,这个微库已经解决了这个问题。

此博客文章中的更多详细信息。

于 2021-02-14T16:01:49.983 回答
1

getProperty抛出异常,而不是错误。重要的是,您可以处理它,并为自己节省if

$ref = new ReflectionObject($obj);
$propName = "myProperty";
try {
  $prop = $ref->getProperty($propName);
} catch (ReflectionException $ex) {
  echo "property $propName does not exist";
  //or echo the exception message: echo $ex->getMessage();
}

要获取所有私有属性,请使用$ref->getProperties(ReflectionProperty::IS_PRIVATE);

于 2012-07-23T00:04:17.003 回答
1

如果您需要它而无需反思:

public function propertyReader(): Closure
{
    return function &($object, $property) {
        $value = &Closure::bind(function &() use ($property) {
            return $this->$property;
        }, $object, $object)->__invoke();
         return $value;
    };
}

然后像这样使用它(在同一个类中):

$object = new SomeObject();
$reader = $this->propertyReader();
$result = &$reader($object, 'some_property');
于 2019-10-30T13:48:29.140 回答