繁体   English   中英

如何使父方法在PHP中使用$ this-> methodName进行调用?

[英]how to make parent method to be called using $this->methodName in PHP?

我有两节课。 一个是父母,另一个是孩子。 两者都有相同的命名方法。 问题是父方法不会使用$ this-> methodName调用。

家长班

class Parent
{

    public function __construct()
    {
        $this->init();
    }

    // this function never get executed and why?
    public function init()
    {

       //do something

    }
}

儿童班

class Child extends Parent
{

   public function __construct()
   {
      parent::__construct();
      $this->init();
   }

   public function init()
   {
   // do something different
   }
}

如何在不使用parent :: init的情况下调用父方法?

您可以使用self来引用当前类。 $this相对,后者在运行时引用当前对象。

class ParentClass
{

    public function __construct()
    {
        self::init();
    }

    public function init()
    {   
        echo 'parent<br/>';
    }
}
<?php
    public function __construct(){
        parent::__construct();
        self::init();
    }
?>

父类中的其他对象还使用self来避免执行父init和子init。

事情是parent::是有原因的,其中一个原因是要处理您遇到的“问题”(这不是问题)。

显然,如果您的子类具有例如myfunction()的功能,而父类具有名为myfunction()的功能,则如果在$this->myfunction()使用$this->myfunction() ,则显然会调用子代的myfunction()函数因为$this是对当前对象的引用。

使用parent没有任何危害,这是有原因的。

暂无
暂无

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

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