PHP\uuu get和私有类变量
假设有一个定义了PHP\uuu get和私有类变量,php,oop,Php,Oop,假设有一个定义了\uu get()的抽象基类foo,以及从foo继承的带有私有变量$var的子类\uu get(),当试图从类外部访问私有$var时,是否会调用父类\uu get() 是的 <?php abstract class foo { public function __get($var) { echo "Parent (Foo) __get() called for $var\n"; }
\uu get()
的抽象基类foo
,以及从foo
继承的带有私有变量$var
的子类\uu get()
,当试图从类外部访问私有$var
时,是否会调用父类\uu get()
是的
<?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
为var调用了Parent(Foo)\uuuu get()
25是的<当访问当前执行不可见的数据成员时,将调用code>\uu get()和\uu set()
(以及\uu call()
)
在这种情况下,$var
是私有的,因此公开访问它将调用\uu get()
钩子