碰到一个问题,直接在控制器中定义__construct()时,会报错。

原因:必须调用父类Controller中的construct函数,所以要在定义的控制器中使用construct函数就必须用parent::__construct();调用父类Controller中的__construct

解决:可以用_initialize(thinkphp封装好的)直接定义一个构造函数省去频繁地调用parent::__construct()

比如:

<?php
class IndexController extends Controller
{
    public function _initialize()
    {
        //检查是否登录
        check_login();
    }

    public function index()
    {
        $this->display("index");
    }
}

调用parent::__construct()的话:

<?php
class IndexController extends Controller
{
    public function __construct()
    {
        parent::__construct();

        //检查是否登录
        check_login();
    }

    public function index()
    {
        $this->display("index");
    }
}