PHP-类中的闭包,获取私有属性


PHP - Closure in class , getting private property

我正试图使用闭包从另一个类获取私有属性,如下所述:

http://ocramius.github.io/blog/accessing-private-php-class-members-without-reflection/

所以,我正试图获得$wheelCount的财产。

但我一直在接受

Fatal error: Cannot access private property Car::$wheelCount

所以我的汽车等级是:

class Car
{
    private $wheelCount = 4;    
    public function __construct($wheely)
    {
             echo $wheely->getWheels($this);
    }
}

然后

   class getThoseWheels
    {
        public function getWheels($that)
        {
            $wheels = Closure::bind($this->getPrivate($that), null, $that);
            var_dump($wheels);

        }
        public function getPrivate($that)
        {
             return $that->wheelCount;
        }
    }

运行的:

$wheely = new getThoseWheels();
new Car($wheely);
$wheels = Closure::bind($this->getPrivate($that), null, $that);

问题是正在执行$this->getPrivate(),而此方法正试图访问private属性。所有这一切都发生在Closure::bind参与之前。你应该这样使用它:

$wheels = Closure::bind(function () { return $this->wheels; }, $that, $that);

或者可能:

$wheels = Closure::bind([$this, 'getPrivate'], null, $that);

我还没有对此进行测试,但至少这比您的代码有更好的成功机会。