ThinkPHP中initialize和construct的不同

來源:互聯網
上載者:User

標籤:

本文轉載自:http://www.kuitao8.com/20140819/2953.shtml

ThinkPHP中initialize()和construct()這兩個函數都可以理解為建構函式,前面一個是tp架構專屬的,後面的是php建構函式,那麼這兩個有什麼不同呢?

 

在網上搜尋,很多答案是兩者是一樣的,ThinkPHP中initialize相當於php的construct,這麼說是錯誤的,如果這樣,tp為什麼不用construct,而要自己弄一個ThinkPHP版的initialize建構函式呢?

 

自己試一下就知道兩者的不同了。

 

a.php

class a{

    function __construct(){

        echo ‘a‘;

    }

}

複製代碼

b.php(注意:這裡建構函式沒有調用parent::__construct();)

include ‘a.php‘;

class b extends a{

    function __construct(){

        echo ‘b‘;

    }

}

 

$test=new b();

複製代碼

運行結果:

b

複製代碼

可見,雖然b類繼承了a類,但是輸出結果證明程式只是執行了b類的建構函式,而沒有自動執行父類的建構函式。

 

如果b.php的建構函式加上parent::__construct(),就不同了。

include ‘a.php‘;

class b extends a{

    function __construct(){

        parent::__construct();

        echo ‘b‘;

    }

}

 

$test=new b();

複製代碼

那麼輸出結果是:

ab

複製代碼

此時才執行了父類的建構函式。

 

我們再來看看thinkphp的initialize()函數。

 

BaseAction.class.php

class BaseAction extends Action{

    public function _initialize(){

             echo ‘baseAction‘;

    }

複製代碼

IndexAction.class.php

class IndexAction extends BaseAction{

    public function (){

             echo ‘indexAction‘;

        }

複製代碼

運行Index下的index方法,輸出結果:

baseActionindexAcition

複製代碼

可見,子類的_initialize方法自動調用父類的_initialize方法。而php的建構函式construct,如果要調用父類的方法,必須在子類建構函式顯示調用parent::__construct();

 

這就是ThinkPHP中initialize和construct的不同。

ThinkPHP中initialize和construct的不同

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.