假设有一个定义了foo
的抽象基类__get()
,以及一个继承自bar
私有变量foo
的子类$var
,在尝试从课堂外访问私有__get()
时,是否会调用父$var
?
答案 0 :(得分:10)
是。
<?php
abstract class foo
{
public function __get($var)
{
echo "Parent (Foo) __get() called for $var\n";
}
}
class bar extends foo
{
private $var;
public function __construct()
{
$this->var = "25\n";
}
public function getVar()
{
return $this->var;
}
}
$obj = new bar();
echo $obj->var;
echo $obj->getVar();
?>
输出:
$ php test.php
父(Foo)__ get()调用var
25
答案 1 :(得分:4)
是。当访问对当前执行不可见的数据成员时,将调用__get()
和__set()
(以及__call()
)。
在这种情况下,$var
是私有的,因此公开访问它会调用__get()
挂钩。