我正在尝试使用闭包从另一个类获取私有属性,如下所述:
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);
答案 0 :(得分:1)
$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);
我没有对此进行测试,但至少这比你的代码有更好的成功机会。