强烈建议TP5要求PHP版本5.5以上

浏览:15044 发布日期:2016/12/08 分类:ThinkPHP5专区
提出这个要求的原因是本人使用TP5时遇到的一些问题,主要是trait的相关操作,具体可以看如下分析!
我们知道 trait 在php5.5以下需要loader一次再使用use php5.5以上可以直接使用use 会自动引入,TP为了兼容php5.4版本,在框架Controller等类引入trait时都采用了Loader::import方法首先引入trait,虽然Loader::import方法存在缓存机制,不会重复引入,但是我们在使用PHP5.5版本以上时,直接使用use ,这样默认就会把相关trait自动引入,而当在后期加载Controller类时,Loader::import方法根本无法识别自动use是否引入过相关文件,而导致重复引入了一次而报错!
首先上几个代码,具体需求是这样,在app_init扩展Init类里面需要使用jump跳转功能代码如下
Init.phpnamespace app\common\behavior;
 //\think\Loader::import('controller/Jump', TRAIT_PATH, EXT); //php5.5以上先暂时注释这句
class Init {
    
    use\traits\controller\Jump;

    public function run(&$params = null) {
        $this->redirect ( __ROOT__ . '/' . config ( 'install_url' ) . '/' );
    }
}
控制器Index.phpnamespace app\index\controller;
\think\Loader::import('controller/Jump', TRAIT_PATH, EXT);
class Index{
    
    use\traits\controller\Jump;
    
    public function index(){
        
        
        
    }
    
}
如上代码所示,如果Init.php里面没有loader,控制器里面用了loader或重复载入报错,由于框架核心Controller类为了兼容php5.4 默认使用了 \think\Loader::import,所以只要继承了think\Controller类,而在前面的所有类种不使用\think\Loader::import引入一次而是直接使用use,那么后面解析到Controller时也会同样出现重复载入报错的问题,所以解决方法是在Init.php里面先使用一次\think\Loader::import先引入,但是这样对于PHP5.5版本以上来说是脱了裤子放屁,一样需要先载入一次!
最佳答案
评论( 相关
后面还有条评论,点击查看>>