温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何解析ThinkPHP5之 _initialize()初始化方法

发布时间:2021-03-18 09:04:00 来源:亿速云 阅读:158 作者:小新 栏目:编程语言

小编给大家分享一下如何解析ThinkPHP5之 _initialize()初始化方法,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!

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

前言

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

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

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

示例

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

namespace app\index\controller;

use think\Controller;

class Index extends Controller
{

    public function _initialize()
    {
        echo 'init<br/>';
    }

    public function hello()
    {
        return 'hello';
    }

    public function data()
    {
        return 'data';
    }
}

如果访问

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('template'), Config::get('view_replace_str'));
        $this->request = $request;

        // 控制器初始化
        if (method_exists($this, '_initialize')) {
            $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, '_initialize')) {
    $this->_initialize();
}

真相出现了有木有?!

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

延伸

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

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

看完了这篇文章,相信你对“如何解析ThinkPHP5之 _initialize()初始化方法”有了一定的了解,如果想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI