为了账号安全,请及时绑定邮箱和手机立即绑定

php反射类如何获取构造方法得到的私有属性

php反射类如何获取构造方法得到的私有属性

PHP
慕工程0101907 2019-03-18 15:24:13
class test{ private $a=array(); public function __construct() { $this->geta (); } private function geta(){ $b [] = 1; $b [] = 2; $this->a = $b; // 没有return } } //反射获取 $ref_class = new ReflectionClass('test'); $geta= $ref_class->newInstance(); $method = $ref_class->getmethod('geta'); $method->setAccessible(true); $a = $method->invoke($rongyuclass); //空的,因为geta不返回任何值 有这样的一个类,现在里面的私有方法geta没有return出任何数据,但是构造方法那边给私有属性a赋值,我直接用反射去取变量$a的时候得到的只能是空值,如何先执行构造,然后得到赋值后的私有属性a?
查看完整描述

2 回答

?
猛跑小猪

TA贡献1858条经验 获得超8个赞

$ref = new ReflectionClass('test');
$a = $ref->getProperty('a');
$a->setAccessible(true); //设置属性a的访问权限
var_dump($a->getValue(new test));

查看完整回答
反对 回复 2019-03-18
?
炎炎设计

TA贡献1808条经验 获得超4个赞

class test{
    private $a=array();
    public function __construct() {
        $this->geta ();
    }
    private function geta(){
        $b [] = 1;
        $b [] = 2;
        
        $this->a = $b;
        // 没有return
    }
}

$test = new test;

$closure = function() {
    return $this->a;
};
// rebinds the closure to the $test object
$closure  = $closure->bindTo($test, $test);
print_r($closure());
查看完整回答
反对 回复 2019-03-18
  • 2 回答
  • 0 关注
  • 642 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信