这段代码为何会输出father?求合理解释?
<?php
class father
{
public function __construct()
{
$this->init();
} private function init()
{
echo "father\n";
}
}class son extends father
{
public function init()
{
echo "son\n";
}
}$son = new son();
<?php
class father
{
public function __construct()
{
$this->init();
} private function init()
{
echo "father\n";
}
}class son extends father
{
public function init()
{
echo "son\n";
}
}$son = new son();
需要解释吗?这和所有的权限系统都是一样的
因为你是new son
因为你是new son我知道,我的意思是,既然这个this是指向son的,那么this->init()不应该是调用son的init吗?那么不就是输出son么,为何输出father?
son::init() 是共有的
根据共有的不能覆盖私有的这个原则
father::init() 不会被 son::init() 覆盖
所以在执行 father::__construct() 时,$this->init() 执行的是 father::init()至于为什是 共有的不能覆盖私有的 而不是别的
那就不太好说了,这是约定俗成的东西,没有什么道理可讲(当然也与西方人的价值观有关)