【发布时间】:2014-05-22 01:16:58
【问题描述】:
我正在玩几个班级来了解父母和孩子之间的关系。我将父级设置为具有调用 init 方法的构造函数。那么当我向子级添加一个init方法时,它应该覆盖父级init,不是吗?但实际情况是这两种方法都被调用了。
为了测试这一点,我编写了一个名为 Model 的类和一个名为 Instance 的子类。代码如下:
$try = new Instance;
echo $try;
class Model{
public function __construct(){
$this->init();
}
public function init()
{
return $this->className();
}
public function __toString()
{
return $this->className();
}
public static function className()
{
return get_called_class();
}
}
class Instance extends Model
{
public function init()
{
echo "tada! ";
}
}
给出以下输出:
tada! Instance.
在类 Model 中,我使用魔术方法 __toString() 将类名作为字符串返回。父类的构造函数调用父类的 init() 方法,在这种情况下与类名相呼应。
我的理解是,如果我编写一个子类,在这种情况下,该类称为 Instance,具有 init() 方法,它会覆盖父 init() 方法,但事实并非如此。在这种情况下,它返回两个初始化方法,我不知道为什么。谁能解释一下?
【问题讨论】:
标签: php methods constructor overriding