gpt4 book ai didi

php - PHP 中是否有一个关键字引用祖父类的成员?

转载 作者:行者123 更新时间:2023-12-02 03:58:24 25 4
gpt4 key购买 nike

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 类中引用 Grandfather 类的成员?

我的第一个想法是Classname::method(),但是是否有可用的关键字,例如selfparent

最佳答案

$this->stuff()或者祖父::stuff()

调用此方法将调用继承级别顶部的 ::stuff() 方法(在您的示例中,它是 Dad::stuff(),但您不会覆盖 Dad 类中的 ::stuff ,因此它是Grandfather::stuff())

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();

“Yeeeh”将输出2次。因为 Dad 的构造函数(在 Kid 类中未重写)类调用 Grandfather::stuff()Kid::doThatStuff () 也调用它

关于php - PHP 中是否有一个关键字引用祖父类的成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28393442/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com