Paw*_*wka 19
从公共访问受保护或私有变量是不正确的(这就是为什么它们受到保护或私有).所以更好的是扩展类和访问所需的属性或使getter方法公开.但是如果你仍然希望获得没有扩展的属性,并且如果你使用PHP 5,你可以使用Reflection类访问.实际上尝试ReflectionProperty类.
class Foo { protected $bar; }
$foo = new Foo();
$rp = new ReflectionProperty('Foo', 'bar');
$rp->setAccessible(true);
echo $rp->getValue($foo);
Run Code Online (Sandbox Code Playgroud)
Kas*_*ncz 14
这是正确的答案:
我们可以使用Closure类的bind()或bindTo方法来访问某些类的私有/受保护数据,例如:
class MyClass {
protected $variable = 'I am protected variable!';
}
$closure = function() {
return $this->variable;
};
$result = Closure::bind($closure, new MyClass(), 'MyClass');
echo $result(); // I am protected variable!
Run Code Online (Sandbox Code Playgroud)
小智 13
只需在课程中添加"get"方法即可.
class Foo
{
protected $bar = 'Hello World!';
public function getBar()
{
return $this->bar;
}
}
$baz = new Foo();
echo $baz->getBar();
Run Code Online (Sandbox Code Playgroud)