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

hen*_*ght 2 php oop

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?
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能从Kid课程中提到祖父班的成员?

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

Kam*_*kus 5

$this->stuff() 要么 Grandfather::stuff()

使用this进行调用将::stuff()在继承级别的顶部调用方法(在您的示例中它将是Dad::stuff(),但您不在类中重写::stuff,Dad所以它是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();
Run Code Online (Sandbox Code Playgroud)

"Yeeeh"将输出2次.因为Dad(Kid类中没有覆盖)类的构造函数调用Grandfather::stuff()Kid::doThatStuff()调用它