ThinkPHP __construct和_initialize的使用

ThinkPHP框架中的__construct和_initialize的使用

父类(PlatformController.class.php):

class PlatformController extends Controller{

    public function __construct(){
        echo 'PlatformController' . "<br>";

        //调用父类的构造函数
        parent::__construct();

        echo 'PlatformController第二次' . "<br>";
    }

 
    protected  function _initialize(){
        echo 'PlatformController下的_initialize'."<br>";
    }
}

子类():

class AdminController extends PlatformController{

    public function __construct(){
        parent::__construct();
//子类需要的逻辑代码,如果不需要,则无需加载构造函数
//...... }
public function test(){ echo 'AdminController'."<br>"; } }

访问子类的test方法,输出结果:

PlatformController
PlatformController下的_initialize
PlatformController第二次
AdminController

结论:

(1)父类的__construct构造方法会自动调用_initialize方法。

(2)子类继承父类后,不需要写构造方法就会自动加载父类的构造函数。

(3)如果子类需要自己的构造函数,写parent::__construct(),才会加载父类构造方法,否则就不加载父类的构造方法。

原文地址:https://www.cnblogs.com/gyfluck/p/9171976.html