2013-06-24 137 views
1

我有以下類PHP init被調用兩次?

class CLG_Container_Main_Schedule extends CLG_Container_Main 
{ 
    protected $_box = 'schedule'; 

    public function __construct($calendar=null) 
    { 
     parent::__construct($this->_box); 
     $this->init(); 
    } 


    public function init() 
    { 
     $this->setTitle('Schedule'); 

     $html = '<div id="schedule_time">'; 
     for($h = 5; $h < 24; $h++) 
     { 
      for($m=0; $m <60; $m += 15) 
      { 
       $time = str_pad($h, 2, '0', STR_PAD_LEFT) . ':' . str_pad($m, 2, '0', STR_PAD_RIGHT); 
       $time_id = str_pad($h, 2, '0', STR_PAD_LEFT) . str_pad($m, 2, '0', STR_PAD_RIGHT); 
       $html .= '<div class="schedule_time" time="' . $time_id . '">' . $time . '</div>'; 
      } 
     } 
     $html .= '</div>'; 
     $this->setContent($html); 
    } 


    public function render() 
    { 
     return parent::render(); 
    } 
} 

出於某種原因,類函數被調用兩次,因爲我得到了$ HTML我創建的兩個實例。奇怪的是,我有另一個容器類,並且還調用init()在構造函數中,但一個只調用一次。

我錯過了什麼?當我從構造函數中刪除init()時,init()被調用了一些方法,並且一切正常。

感謝

+1

'CLG_Container_Main'還在其構造函數中調用init()嗎? –

+0

火了一個調試器,並設置在構造一個斷點。看看堆棧跟蹤,看看是什麼調用它。 – Matt

+0

是的,CLG_Container_Main還調用init(),但應該運行init是主?或者我需要給他們不同的名字? – user1083320

回答

2

由於init()parent::__construct(..)你不需要從子構造函數中調用它叫。當類創建時,PHP將調用正確的init()方法。

您已經驗證了這一點,當你從你的子類刪除調用init,一切工作正常。

可以通過運行這個簡單的例子,反映了或多或少什麼在你的代碼是怎麼回事驗證這一點。

<?php 

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

    public function init() { 
     echo "init parent\n"; 
    } 
} 


class AChild extends AParent { 

    public function __construct(){ 
     parent::__construct(); 
    } 

    public function init(){ 
     echo "init child\n" ; 
    } 
} 

new AParent(); // Calls init from AParent 
new AChild(); // Calls init from AChild 
+0

幾乎我在評論中所忽略的。 –