construct()是php的构造函数,在子类继承父类的时候,需要显示的调用父类的构造函数,默认是不调用父类的构造函数.
namespace app\two\controller;
class Father
{
public function __construct()
{
echo 'father_construct';
}
}
namespace app\two\controller;
class Son extends Father
{
public function __construct()
{
parent::__construct();
echo 'son_construct';
}
public function index()
{
}
}
当访问子类的index方法时,会优先调用Son类中的__construct,然后再调用Father类中的__construct。为什么会调用Father类中的__construct呢?因为,在Son的__construct中,明确显示
调用了parent::__construct();所以会执行父类的构造函数。
由此课件,__construct构造,在当前类中,是默认调用,即使不通过new关键字创建当前类的对象,也是调用的。这里的index()方法,并没有任何操作,访问直接输出:
father_constructson_construct
再来看看initialize,
initialize()这是控制器独有的初始化方法,并且,当前使用initialize()的控制器,必须继承Controller,或者其父类必须继承Controller,否则不能使用。
namespace app\two\controller;
use think\Controller;
class Father extends Controller
{
protected function initialize()
{
echo 'father_initialize';
}
}
namespace app\two\controller;
class Son extends Father
{
protected function initialize()
{
//添加上此行,说明需要调用父类的初始化方法,如果不添加,则不调用父类的初始化方法
parent::initialize();
echo 'son_initialize';
}
public function index()
{
return '123';
}
}
结果输出:father_initializeson_initialize123
这两个函数最大的区别:initialize()必须是Controller的子孙继承者,才能使用,__construct()只要是class就可以使用。