首页 > 解决方案 > PHP:如何通过反射或其他方式从子类获取父抽象类私有属性

问题描述

我有这样的情况。

所以我们有father具有私有$secret属性的抽象。

abstract class father{
    private $secret = 'my_secret';
}

还有一个儿童班

class child extends father{
    public function getFatherSecret(){
        // some code to get a private prop
    }
}

我不知道也许这是不可能的。

因此,我需要获得一个父私有属性,例如Closure 绑定方法或反序列化方法,这些方法已经在一些 PHP 文档中进行了充分解释。

标签: php

解决方案


虽然我对这种方法的使用有各种保留意见,但总是有回答问题的原则(即使是纯学术意义上的)。

所以...

abstract class father{
    private $secret = 'my_secret';
}

class child extends father{
    public function getFatherSecret(){
        $closure = Closure::bind(function (father $f) { return $f->secret; }, 
            null, "father");

        print_r($closure($this));
    }
}

$c = new child();
$c->getFatherSecret();

给...

my_secret

推荐阅读