(不懂类的请自行百度)
就是在使用类之前该类已经加载好一些公共的功能,比如判断登陆等等...
怎么写类的初始化?
就是使用php唯一的构造函数__construct()
这是两个类
<?php
namespace app\index\controller;
use \think\Controller;
class Home extends Controller{
}<?php
namespace app\index\controller;
use app\index\controller\Home;
class Index extends Home{
}其中index继承了home如果我在父类中写构造方法
<?php
namespace app\index\controller;
use \think\Controller;
class Home extends Controller{
public function __construct(){
parent::__construct();
echo 123;
}
}<?php
namespace app\index\controller;
use app\index\controller\Home;
class Index extends Home{
}此时调用子类的话输出的是123这说明子类会自动调用父类的构造函数
但是如果子类有自己的构造函数的话呢
<?php
namespace app\index\controller;
use \think\Controller;
class Home extends Controller{
public function __construct(){
parent::__construct();
echo 123;
}
}<?php
namespace app\index\controller;
use app\index\controller\Home;
class Index extends Home{
public function __construct(){
echo 456;
}
}此时调用子类的话输出的是456说明子类存在构造函数的时候并不会调用父类的构造函数
那这时候只要在子类的构造函数中加入parent::__construct();就行了
<?php
namespace app\index\controller;
use \think\Controller;
class Home extends Controller{
public function __construct(){
parent::__construct();
echo 123;
}
}<?php
namespace app\index\controller;
use app\index\controller\Home;
class Index extends Home{
public function __construct(){
parent::__construct();
echo 456;
}
}此时调用子类的话输出的是123456这时子类和父类的构造方法都会执行
如果有许多的子类都要调用同一个父类就需要写好多的 parent::__construct();
tp为了简化于是就出现了__initialize()
<?php
namespace app\index\controller;
use \think\Controller;
class Home extends Controller{
public function __construct(){
parent::__construct();
if(method_exists($this,'_initialize')){
$this->_initialize();
}
}
}<?php
namespace app\index\controller;
use app\index\controller\Home;
class Index extends Home{
public function _initialize(){
echo 555;
}我们只要这么写子类和父类的构造方法就都会执行了。 最佳答案