ErrorException in TestABC.php line 41



未定义数组索引: key


die();

 
//        require_once VENDOR_PATH.'topthink/think-captcha/src/Captcha.php';

 
//        return (new \think\captcha\Captcha()) -> entry();

 
        return captcha_img();

 
        return json(['checkCode'=>captcha_src(),'token'=>createUUID()]);

 
    }

 


 
    public function myTest(){

 
        $a = [];

 
        echo $a['key'];

 
    }

 
}
 

       die();

//        require_once VENDOR_PATH.'topthink/think-captcha/src/Captcha.php';

//        return (new \think\captcha\Captcha()) -> entry();

        return captcha_img();

        return json(['checkCode'=>captcha_src(),'token'=>createUUID()]);

    }



    public function myTest(){

        $a = [];

        echo $a['key'];

    }

}


估计很多人在使用tp5框架或者迁移项目换了tp5框架时,由于代码的不规范(变量未声明就直接使用),很容易出现这种Notice级别的报错,其原因在于:

1.  public/目录下的入口文件:index.php


require __DIR__ . '/../thinkphp/start.php';

 2. thinkphp/目录下的start.php


namespace think;

// ThinkPHP 引导文件
// 加载基础文件
require __DIR__ . '/base.php';
// 执行应用
App::run()->send();
3. base.php文件定义了核心常量及加载类文件。
// 注册自动加载
\think\Loader::register();

// 注册错误和异常处理机制
\think\Error::register();

// 加载惯例配置文件
\think\Config::set(include THINK_PATH . 'convention' . EXT);
注意Error::register();该文件Error.php位入thinkphp/library/think/Error.php
public static function register()
{
    error_reporting(E_ALL);
    set_error_handler([__CLASS__, 'appError']);
    set_exception_handler([__CLASS__, 'appException']);
    register_shutdown_function([__CLASS__, 'appShutdown']);
}error_reporting(E_ALL);也就是报告任何错误。
然后看tp5手册对《错误与调试》部分对此的说明:
本着严谨的原则,5.0版本默认情况下会对任何错误(包括警告错误)抛出异常,如果不希望如此严谨的抛出异常,
error_reporting
例如:
error_reporting(E_ERROR | E_PARSE );
因此,根据tp5框架加载原则,即使在入口文件添加了error_reporting(E_ERROR | E_PARSE )依然无效,因为会被后面的代码覆盖。
故参考tp手册,我们可以在项目目录application/Module/下的common.php或者config.php下文件添加
error_reporting(E_ERROR | E_PARSE );
注意:config.php添加error_reporting(E_ERROR | E_PARSE );要在return [];之前添加。
当然,除了以上两种方式外,我们还可以在控制器代码添加error_reporting(E_ERROR | E_PARSE );来避免代码不规范引起的频繁报错。
个人建议最好是在config.php文件添加以上代码。按照tp5文件加载顺序,应用配置文件config.php优先于common.php加载。





以上代码均由本人亲自测试有效:

总结:解决notice、warning报错的方案有

1. 修改框架源码(强烈建议不要使用此方法,破坏框架设计原则--代码严谨性

error_reporting(E_ALL);

修改为error_reporting(E_ERROR | E_PARSE );

2.应用配置文件config.php添加(如果忽略代码严谨性原则,强烈推荐使用)

error_reporting(E_ERROR | E_PARSE );

3.应用公共文件common.php添加

error_reporting(E_ERROR | E_PARSE );

4.控制器添加(此方式只对本控制器执行的代码有效,并非全局有效,作局部屏蔽使用。

error_reporting(E_ERROR | E_PARSE );

5.根据4衍生而来,建立Base控制器此方式对所有控制器均有效。

Base控制器 extends \think\Controller,然后添加如下代码

public function _initialize(){
    parent::_initialize();
    error_reporting(E_ERROR | E_PARSE );
}

然后让所有控制器都继承Base控制器即可。


最后,本着代码严谨性原则,遵循开发规范,强烈推荐大家在开发中不要忽略notice和warning错误的报告。问题早发现,早解决。