/** * 架构函数 取得模板对象实例 * @access public */ public function __construct() { Hook::listen(‘action_begin‘,$this->config); //实例化视图类 $this->view = Think::instance(‘Think\View‘); //控制器初始化 if(method_exists($this,‘_initialize‘)) $this->_initialize(); }
从Controller类中的构造函数中可以知道,该构造函数会判断对象中是否有_initialize方法,如果有,就执行先_initialize方法,
<?php namespace Home\Controller; use Think\Controller; class IndexController extends Controller { public function __construct() { parent::__construct(); self::b(); echo ‘我是构造<br />‘; } public function _initialize() { echo ‘我先来<br />‘; // parent::_initialize(); } public function index(){ self::b(); echo ‘这是index‘; } public function b() { echo ‘bbbb<br />‘; } } /* 当执行index方法时,打印结果: 我先来 bbbb 我是构造 bbbb 这是index */
<?php namespace Home\Controller; use Think\Controller; class IndexController extends Controller { public function __construct() { // parent::__construct(); self::b(); echo ‘我是构造<br />‘; } public function _initialize() { echo ‘我先来<br />‘; // parent::_initialize(); } public function index(){ self::b(); echo ‘这是index‘; } public function b() { echo ‘bbbb<br />‘; } } /* 当执行index方法时,打印结果: bbbb 我是构造 bbbb 这是index */
<?php namespace Home\Controller; use Think\Controller; class IndexController extends Controller { // public function __construct() { // // parent::__construct(); // self::b(); // echo ‘我是构造<br />‘; // } public function _initialize() { echo ‘我先来<br />‘; // parent::_initialize(); } public function index(){ self::b(); echo ‘这是index‘; } public function b() { echo ‘bbbb<br />‘; } } /* 当执行index方法时,打印结果: 我先来 bbbb 这是index
<?php namespace Home\Controller; use Think\Controller; class BaseController extends Controller { public function __construct() { parent::__construct(); echo ‘我是父类<br />‘; } public function _initialize() { echo ‘我先来<br />‘; } public function a() { echo ‘aaaa<br />‘; } }
<?php namespace Home\Controller; use Think\Controller; class IndexController extends BaseController { public function __construct() { parent::__construct(); self::b(); echo ‘我是构造<br />‘; } public function _initialize() { parent::_initialize(); echo ‘我是子类先来<br />‘; } public function index(){ self::b(); echo ‘这是index‘; } public function b() { echo ‘bbbb<br />‘; } } /* 当执行index方法时,打印结果: 我先来 我是子类先来 我是父类 bbbb 我是构造 bbbb 这是index
更多学习内容请访问:
腾讯T3-T4标准精品PHP架构师教程目录大全,只要你看完保证薪资上升一个台阶(持续更新)?
thinkphp中__construct()和__initialize()的介绍
原文:https://www.cnblogs.com/a609251438/p/12767228.html