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

时间:2015-02-08 11:33:10

标签: 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?
}

我怎样才能在Kid课程中引用祖父班的成员?

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

3 个答案:

答案 0 :(得分:5)

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

使用此方法调用将在继承级别的顶部调用::stuff()方法 (在您的示例中,它是Dad::stuff(),但您不能覆盖::stuff课程中的Dad,因此它会Grandfather::stuff())< / p>

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

&#34; Yeeeh&#34;将被输出2次。因为Dad的构造函数(在Kid类中未被覆盖)类调用Grandfather::stuff()Kid::doThatStuff()调用它

答案 1 :(得分:3)

  1. 如果stuff()在类层次结构中无法覆盖,则可以使用$this->stuff()
  2. 调用该函数
  3. 如果要在stuff()中覆盖Dad,则必须使用类名调用该函数,例如Grandfather::stuff()
  4. 如果在stuff()中覆盖Kid,您可以通过parent::stuff()
  5. 拨打电话

答案 2 :(得分:1)

如果您想调用祖父:: stuff方法,可以使用Grandfather::stuff()课程中的Kid执行此操作。

看看这个example