TP框架中的__construct()和__initialize()

ThinkPHP中的__initialize()和类的构造函数__construct()
网上有很多关于__initialize()的说法和用法,总感觉不对头,所以自己测试了一下。将结果和大家分享。不对请更正。
首先,我要说的是
1、__initialize()不是php类中的函数,php类的构造函数只有__construct().
2、类的初始化:子类如果有自己的构造函数(__construct()),则调用自己的进行初始化,如果没有,则调用父类的构造函数进行自己的初始化。
3、当子类和父类都有__construct()函数的时候,如果要在初始化子类的时候同时调用父类的__constrcut(),则可以在子类中使用parent::__construct().
如果我们写两个类,如下

class Action{
    public function __construct()
    {
        echo 'hello Action';
    }
}
class IndexAction extends Action{
    public function __construct()
    {
        echo 'hello IndexAction';
    }
}
$test = new IndexAction;
//output --- hello IndexAction

很明显初始化子类IndexAction的时候会调用自己的构造器,所以输出是'hello IndexAction'。
但是将子类修改为:

class IndexAction extends Action{
    public function __initialize()
    {
        echo 'hello IndexAction';
    }
}

那么输出的是'hello Action'。因为子类IndexAction没有自己的构造器。
如果我想在初始化子类的时候,同时调用父类的构造器呢?

class IndexAction extends Action{
    public function __construct()
    {
        parent::__construct();
        echo 'hello IndexAction';
    }
}
复制代码

这样就可以将两句话同时输出。
当然还有一种办法就是在父类中调用子类的方法。

class Action{
    public function __construct()
    {
        if(method_exists($this,'hello'))
        {
            $this -> hello();
        }
        echo 'hello Action';
    }
}
class IndexAction extends Action{
    public function hello()
    {
        echo 'hello IndexAction';
    }
}

这样也可以将两句话同时输出。
而,这里子类中的方法hello()就类似于ThinkPHP中__initialize()。
所以,ThinkPHP中的__initialize()的出现只是方便程序员在写子类的时候避免频繁的使用parent::__construct(),同时正确的调用框架内父类的构造器,所以,我们在ThnikPHP中初始化子类的时候要用__initialize(),而不用__construct(),当然你也可以通过修改框架将__initialize()函数修改为你喜欢的函数名。

 

 

 

以下是我自己的代码,上面的是别的地方拷贝过来的。

<?php

namespace app\admin\controller;

use think\controller;
use think\Request;

class Common extends Controller //Common的父类是Controller,Controller有自己的构造方法。
{
    public function __construct(Request $request = null)//请注意,构造方法是类实例化的时候,自动执行的第一个方法。
    {
        parent::__construct($request);//子类有构造方法的时候,还需要用到父类的构造方法,则需要这句话。
        //执行登录验证,以下相当于$_SESSION['admin']['admin_id'],这个写法在TP框架中不能用了。
        if (!session('admin.admin_id')) {
            $this->redirect('admin/login/login');
        }
    }
}

 

function __construct(){},方法是类被实例化之后,自动执行的第一个方法。为对象的成员变量赋初始值。

 

转载于:https://www.cnblogs.com/windyet/articles/7236503.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值