鍍金池/ 問答/PHP  HTML/ php反射類如何獲取構(gòu)造方法得到的私有屬性

php反射類如何獲取構(gòu)造方法得到的私有屬性

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不返回任何值

有這樣的一個類,現(xiàn)在里面的私有方法geta沒有return出任何數(shù)據(jù),但是構(gòu)造方法那邊給私有屬性a賦值,我直接用反射去取變量$a的時候得到的只能是空值,如何先執(zhí)行構(gòu)造,然后得到賦值后的私有屬性a?

回答
編輯回答
清夢

$ref = new ReflectionClass('test');
$a = $ref->getProperty('a');
$a->setAccessible(true); //設(shè)置屬性a的訪問權(quán)限
var_dump($a->getValue(new test));

2018年4月28日 15:27
編輯回答
殘淚
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());
2017年6月13日 03:37