簡體   English   中英

PHP:如何通過反射或其他方式從子 class 獲取父抽象 class 私有屬性

[英]PHP: How to get parent abstract class private property from child class with reflections or with another way

我有這樣的情況。

所以我們有具有私有$secret屬性的抽象father

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

並且還有一個孩子class

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

我不知道也許這是不可能的。

因此,我需要獲得一個父私有屬性,如Closure 綁定方法或反序列化方法,這些方法已經在一些 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM