class Grandfather {
protected function stuff() {
// Code.
}
}
class Dad extends Grandfather {
function __construct() {
// I can refer to a member in the parent class easily.
parent::stuff();
}
}
class Kid extends Dad {
// How do I refer to the stuff() method which is inside the Grandfather class from here?
}
我怎样才能在Kid课程中引用祖父班的成员?
我的第一个想法是Classname::method()
但有一个关键字可用,例如self
或parent
?
答案 0 :(得分:5)
$this->stuff()
要么
Grandfather::stuff()
使用此方法调用将在继承级别的顶部调用::stuff()
方法
(在您的示例中,它是Dad::stuff()
,但您不能覆盖::stuff
课程中的Dad
,因此它会Grandfather::stuff()
)< / p>
和Class::method()
将调用精确类方法
示例代码:
<?php
class Grandfather {
protected function stuff() {
echo "Yeeeh";
// Code.
}
}
class Dad extends Grandfather {
function __construct() {
// I can refer to a member in the parent class easily.
parent::stuff();
}
}
class Kid extends Dad {
public function doThatStuff(){
Grandfather::stuff();
}
// How do I refer to the stuff() method which is inside the Grandfather class from here?
}
$Kid = new Kid();
$Kid->doThatStuff();
&#34; Yeeeh&#34;将被输出2次。因为Dad
的构造函数(在Kid
类中未被覆盖)类调用Grandfather::stuff()
和Kid::doThatStuff()
调用它
答案 1 :(得分:3)
stuff()
在类层次结构中无法覆盖,则可以使用$this->stuff()
stuff()
中覆盖Dad
,则必须使用类名调用该函数,例如Grandfather::stuff()
stuff()
中覆盖Kid
,您可以通过parent::stuff()
答案 2 :(得分:1)
如果您想调用祖父:: stuff方法,可以使用Grandfather::stuff()
课程中的Kid
执行此操作。
看看这个example。