溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

construct()與initialize()在ThinkPHP中的區(qū)別是什么

發(fā)布時間:2021-01-13 15:30:06 來源:億速云 閱讀:164 作者:Leah 欄目:開發(fā)技術

這期內容當中小編將會給大家?guī)碛嘘Pconstruct()與initialize()在ThinkPHP中的區(qū)別是什么,文章內容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。

創(chuàng)建的FatherAction.class.php文件

<?php


class FatherAction extends Action{
  public function __construct(){
    echo 'father';
  }
}

?>

創(chuàng)建的SonAction.class.php文件

<?php


class SonAction extends FatherAction{
  public function __construct(){
    echo 'son';
  }
function index(){

}
}

?>

運行子類SonAction里的index()可以看到輸出的結果:

son

如果將子類改為:

<?php


class SonAction extends FatherAction{
   public function __construct(){
    parent::__construct();
    echo 'son';
   }
  function index(){

  }
}

?>

運行結果為;

fatherson

上面的結果可以得出結論:

在執(zhí)行子類的構造函數時并不會自動調用父類的構造函數,如果你要調用的話,那么要加上parent::__construct()

當我們把上述的構造方法改為THINKPHP_initialize()方法時運行會發(fā)現:結果與前面的一致,若要執(zhí)行父類的_initialize()方法,也需要使用這一句:parent::_initialize()

那是不是說明php自帶的構造函數__construct()與THINKPHP的_initialize()方法一樣的呢?

先貼上兩段代碼:

<?php


class FatherAction extends Action{
  public function __construct(){
    echo 'father';
  }
}

?>
<?php


class SonAction extends FatherAction{
  public function _initialize(){
    echo 'son';
  }


  function index(){

  }

}

?>

當執(zhí)行子類SonAction的index方法時發(fā)現,輸出的結果為:father

即子類調用了父類的構造函數,而沒有調用子類的_initialize()方法

再貼上兩段代碼:

<?php


class FatherAction extends Action{
  public function __construct(){
    if(method_exists($this,"hello")){
      $this->hello();
    }
    echo 'father';
  }
}

?>
<?php


class SonAction extends FatherAction{
  public function _initialize(){
    echo 'son';
  }
  function index(){

  }

  function hello(){
    echo 'hello';
  }
}

?>

執(zhí)行子類SonAction的index方法,發(fā)現輸入的結果為hellofather

由此可以得出結論:

  當THINKPHP的父類有構造函數而子類沒有時,THINKPHP不會去執(zhí)行子類的_initialize() ;

  當THINKPHP的父類子類均有構造函數時,要調用父類的構造函數必須使用parent::__construct() ----------------- _initialize()同理;

  當THINKPHP的子類同時存在__construct構造函數和_initialize()方法,只會執(zhí)行子類的__construct構造函數(這個本人親測,上述代碼沒有)。

上述就是小編為大家分享的construct()與initialize()在ThinkPHP中的區(qū)別是什么了,如果剛好有類似的疑惑,不妨參照上述分析進行理解。如果想知道更多相關知識,歡迎關注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI