Php 我能通过反射得到私有财产的价值吗?

Php 我能通过反射得到私有财产的价值吗?,php,reflection,Php,Reflection,它似乎不起作用: $ref = new ReflectionObject($obj); if($ref->hasProperty('privateProperty')){ print_r($ref->getProperty('privateProperty')); } 它进入IF循环,然后抛出一个错误: 属性privateProperty不存在 :| $ref=newReflectionProperty($obj,'privateProperty')也不起作用 列出了一些常量

它似乎不起作用:

$ref = new ReflectionObject($obj);

if($ref->hasProperty('privateProperty')){
  print_r($ref->getProperty('privateProperty'));
}
它进入IF循环,然后抛出一个错误:

属性privateProperty不存在

:|

$ref=newReflectionProperty($obj,'privateProperty')
也不起作用

列出了一些常量,包括
是私有的
。如果我不能访问私有财产lol,我怎么能使用它呢?

class a
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));
{ 私人$b='c'; } $obj=新的A(); $r=新的反射对象($obj); $p=$r->getProperty('b'); $p->setAccessible(true);//getValue($obj));
getProperty
引发异常,而不是错误。重要的是,您可以处理它,并在以下情况下为自己保存一个

$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)

以防您需要它而无需反射:

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');

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

这是你可以信赖的

而且,这一问题已经在中得到解决


更多详细信息,请参见。

IS_PRIVATE和other这些常量适用于getProperties(复数-非getProperty)方法您的示例似乎可行,但我的示例不适用:(可能是因为我的班级是儿童班吗?@Alex:看看他们之间的区别吧。你肯定有什么不同之处missed@Alex:是的,
private
仅对创建它们的类可见。但是在这种情况下,
hasProperty
将返回
false
就是这样:s..有什么方法可以获取子类属性吗?I我知道这个问题已经很老了,但我只是浪费了一些时间来搜索如何从孩子那里访问父母的私有属性值,并阅读这些不完整的答案,我希望这能节省一些人的时间:
p=$r->getParentClass()->getProperty('b'))
抬头,
是私有的
应该是
反射属性::是私有的