Heim  >  Artikel  >  Backend-Entwicklung  >  ThinkPHP5之 _initialize() 初始化方法详解

ThinkPHP5之 _initialize() 初始化方法详解

高洛峰
高洛峰Original
2016-11-16 11:26:155475Durchsuche

前言
_initialize() 这个方法在官方手册里是这样说的:

如果你的控制器类继承了\think\Controller类的话,可以定义控制器初始化方法_initialize,在该控制器的方法调用之前首先执行。

其实不止5,在之前的版本中也出现过,这里和大家聊一聊它的实现过程吧。

示例
下面是官方手册上给的示例:

namespace app\index\controller;
use think\Controller;
class Index extends Controller
{
    public function _initialize()
    {
        echo &#39;init<br/>&#39;;
    }
    public function hello()
    {
        return &#39;hello&#39;;
    }
    public function data()
    {
        return &#39;data&#39;;
    }
}

如果访问
http://localhost/index.php/index/Index/hello
会输出

 init
 hello

如果访问
http://localhost/index.php/index/Index/data
会输出

init
data

分析
因为使用必须要继承\think\Controller类,加上这个又是初始化,所以我们首先就想到了\think\Controller类中的 __construct(),一起来看代码:

/**
     * 架构函数
     * @param Request    $request     Request对象
     * @access public
     */
    public function __construct(Request $request = null)
    {
        if (is_null($request)) {
            $request = Request::instance();
        }
        $this->view    = View::instance(Config::get(&#39;template&#39;), Config::get(&#39;view_replace_str&#39;));
        $this->request = $request;
        // 控制器初始化
        if (method_exists($this, &#39;_initialize&#39;)) {
            $this->_initialize();
        }
        // 前置操作方法
        if ($this->beforeActionList) {
            foreach ($this->beforeActionList as $method => $options) {
                is_numeric($method) ?
                $this->beforeAction($options) :
                $this->beforeAction($method, $options);
            }
        }
    }

细心的你一定注意到了,在整个构造函数中,有一个控制器初始化的注释,而下面代码就是实现这个初始化的关键:

// 控制器初始化
if (method_exists($this, &#39;_initialize&#39;)) {
    $this->_initialize();
}

真相出现了有木有?!

其实就是当子类继承父类后,在没有重写构造函数的情况下,也自然继承了父类的构造函数,相应的,进行判断当前类中是否存在 _initialize 方法,有的话就执行,这就是所谓的控制器初始化的原理。

延伸
如果子类继承了父类后,重写了构造方法,注意调用父类的__construct()哦,否则是使用不了的,代码如下:

public function __construct()
{
    parent::__construct();
    ...其他代码...
}

总结
一个简单的小设计,这里抛砖引玉的分析下,希望对大家有帮助。

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Vorheriger Artikel:PHP类方法重写原则Nächster Artikel:php语法基础