__construct 與 ThinkPhp _initialize 的區別


一開始,不怎么了解這個東西,所以最近想到了就來研究一下這個東西。

首先,我就先說說php中的繼承,__construct是類中的構造函數,用於實例化

 1 <?php
 2     class Action{
 3         public function __construct(){
 4             echo 'Action';
 5         }
 6     }
 7 
 8     class SonAction extends Action{
 9         public function __construct(){
10             echo 'Son Action';
11         }
12     }
13 
14     $son = new SonAction();
15 
16     //result:Son Action
17 ?>

在父類中定義構造函數,子類中使用構造函數,示例化子類,輸出Son Action,沒有調用父類中的構造函數

<?php
    class Action{
        public function __construct(){
            echo 'Action';
        }
    }

    class SonAction extends Action{
        public function __construct(){
            parent::__construct();
            echo 'Son Action';
        }
    }

    $son = new SonAction();

    //result:ActionSon Action
?>

在子類中,使用parent::__construct(),調用父類的構造函數,因為繼承了父類,定義自己的構造方法,重載了__construct(),所以需要調用父類的構造函數,需要parent::__construct

<?php
    class Action{
        public function __construct(){
            echo 'Action';
        }
    }

    class SonAction extends Action{

    }

    $son = new SonAction();

    //result:Action
?>

在繼承的子類中沒有自己的構造函數,可以說是繼承了父類的構造函數(個人理解,可以探討一下),所以實例化的時候,輸出得到result

//接下來我說說_initialize 這個函數

其實這個函數不是原生php含有的,而是一個TP自己定義的一個函數

我們可以再TP的框架上看到,我的版本是3.1.3

   /**
     * 架構函數 取得模板對象實例
     * @access public
     */
    public function __construct() {
        tag('action_begin',$this->config);
        //實例化視圖類
        $this->view     = Think::instance('View');           
        //控制器初始化
        if(method_exists($this,'_initialize'))
            $this->_initialize();
    }

這個函數是Action中的構造函數,在控制器初始化中,使用了method_exists,判斷當前實例化的類中是否函數_initialize這個函數,

當子類沒有構造函數的時候,子類繼承父類的構造函數(子類會繼承[或調用最近父類的構造函數]),判斷子類中是否含有_initialize這個函數,

若含有,調用函數,在構造的時候調用該函數,在construct之后。。。。。

下面這個例子:可以仔細觀察出來

 Action類的構造器
    public function __construct() {
        echo  'grand father';
        tag('action_begin',$this->config);
        //實例化視圖類
        $this->view     = Think::instance('View');           
        //控制器初始化
        if(method_exists($this,'_initialize'))
            $this->_initialize();
    }

 TestAction類的構造器
    class TestAction extends Action{
        
        public function __construct(){
            echo 'Test override Action';
        }
    }

  SonatestAction類初始化函數
    class SontestAction extends TestAction{
        public function _initialize(){
            echo 'Son test';
        }
        
        public function index(){
            echo 222;
            die();
        }
    }


  //輸出得到Test override Action222
  

上面的例子得到結果分析可得到: TestAction重載了Action中的構造器,所以訪問SontestAction中的index的時候,首先會調用構造函數,則會調用父類的構造器,父類構造器中不含有調用_initialize所以。。。子類中沒有調用_initialize

哪里有錯誤可以留言討論。

轉載請注明轉載地址,原創有毒,轉載送菊花:http://i.cnblogs.com/EditPosts.aspx?postid=4204198&update=1


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM