我有以下类
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()会被调用一些方式,一切都很好。
感谢
由于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