简体   繁体   English

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

[英]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()但是有一个关键字可用,如selfparent

$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()调用它

  1. If stuff() is nowhere overriden in the class hierarchy you can call the function with $this->stuff() 如果stuff()在类层次结构中无处覆盖,则可以使用$this->stuff()调用该函数
  2. If stuff() were to be overriden in Dad you have to call the function with the classname, eg Grandfather::stuff() 如果要在Dad覆盖stuff() ,你必须用类名调用函数,例如Grandfather::stuff()
  3. If stuff() is overriden in Kid , you can do the call via parent::stuff() 如果在Kid覆盖了stuff() ,你可以通过parent::stuff()调用

If you want call Grandfather::stuff method you can do this using Grandfather::stuff() in Kid class. 如果你想调用祖父:: stuff方法,你可以使用Kid类中的Grandfather::stuff()

Look at this example . 看看这个例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM