[英]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?
}
How can I refer to a member of the Grandfather class from within the Kid class? 我怎样才能从Kid课程中提到祖父班的成员?
My first thought was Classname::method()
but is there a keyword available such as self
or parent
? 我的第一个想法是
Classname::method()
但是有一个关键字可用,如self
或parent
?
$this->stuff()
or Grandfather::stuff()
$this->stuff()
或Grandfather::stuff()
calling with this will call ::stuff()
method on the top of inherit level (in your example it'd be Dad::stuff()
, but you don't override ::stuff
in Dad
class so it'd be Grandfather::stuff()
) 用这个调用会在继承级别的顶部调用
::stuff()
方法(在你的例子中它是Dad::stuff()
,但你不要在Dad
类中覆盖::stuff
所以它是Grandfather::stuff()
)
and Class::method()
will call exact class method 和
Class::method()
将调用精确类方法
Example code: 示例代码:
<?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();
The "Yeeeh" will be outputted 2 times. “Yeeeh”将输出2次。 Because constructor of
Dad
(which is not overrided in Kid
class) class calls Grandfather::stuff()
and Kid::doThatStuff()
calls it too 因为
Dad
构造函数(在Kid
类中未被覆盖)类调用Grandfather::stuff()
而Kid::doThatStuff()
调用它
stuff()
is nowhere overriden in the class hierarchy you can call the function with $this->stuff()
stuff()
在类层次结构中无处覆盖,则可以使用$this->stuff()
调用该函数 stuff()
were to be overriden in Dad
you have to call the function with the classname, eg Grandfather::stuff()
Dad
覆盖stuff()
,你必须用类名调用函数,例如Grandfather::stuff()
stuff()
is overriden in Kid
, you can do the call via parent::stuff()
Kid
覆盖了stuff()
,你可以通过parent::stuff()
调用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.