PHP中是否有关键字引用祖父class的成员?
Is there a keyword that refers to a member of a grandfather class in PHP?
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 class 中引用 Grandfather class 的成员?
我的第一个想法是 Classname::method()
但是否有可用的关键字,例如 self
或 parent
?
- 如果
stuff()
在 class 层次结构中没有被覆盖,您可以使用 $this->stuff()
调用该函数
- 如果
stuff()
在 Dad
中被覆盖,您必须使用 class 名称调用该函数,例如Grandfather::stuff()
- 如果
stuff()
在 Kid
中被覆盖,您可以通过 parent::stuff()
进行调用
如果你想调用 Grandfather::stuff 方法,你可以使用 Grandfather::stuff()
in Kid
class.
看看这个example。
$this->stuff()
要么
Grandfather::stuff()
调用此方法将调用继承级别顶部的 ::stuff()
方法
(在你的例子中它会是 Dad::stuff()
,但你不会在 Dad
class 中覆盖 ::stuff
所以它会是 Grandfather::stuff()
)
和Class::method()
将调用精确的class方法
示例代码:
<?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();
"Yeeeh"会输出2次。因为 Dad
的构造函数(在 Kid
class 中未被覆盖)class 调用 Grandfather::stuff()
而 Kid::doThatStuff()
也调用它
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 class 中引用 Grandfather class 的成员?
我的第一个想法是 Classname::method()
但是否有可用的关键字,例如 self
或 parent
?
- 如果
stuff()
在 class 层次结构中没有被覆盖,您可以使用$this->stuff()
调用该函数
- 如果
stuff()
在Dad
中被覆盖,您必须使用 class 名称调用该函数,例如Grandfather::stuff()
- 如果
stuff()
在Kid
中被覆盖,您可以通过parent::stuff()
进行调用
如果你想调用 Grandfather::stuff 方法,你可以使用 Grandfather::stuff()
in Kid
class.
看看这个example。
$this->stuff()
要么
Grandfather::stuff()
调用此方法将调用继承级别顶部的 ::stuff()
方法
(在你的例子中它会是 Dad::stuff()
,但你不会在 Dad
class 中覆盖 ::stuff
所以它会是 Grandfather::stuff()
)
和Class::method()
将调用精确的class方法
示例代码:
<?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();
"Yeeeh"会输出2次。因为 Dad
的构造函数(在 Kid
class 中未被覆盖)class 调用 Grandfather::stuff()
而 Kid::doThatStuff()
也调用它