簡體   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