| 
                        副标题[/!--empirenews.page--]
                         PHP的错误机制也是非常复杂的,做了几年php,也没有仔细总结过,现在就补上这一课。 
特别说明:文章的PHP版本使用5.5.32 
  
PHP的错误级别 
首先需要了解php有哪些错误。截至到php5.5,一共有16个错误级别 
注意:尝试下面的代码的时候请确保打开error_log: 
- error_reporting(E_ALL);  
 - ini_set('display_errors', 'On');  
 
  
E_ERROR 
这种错误是致命错误,会在页面显示Fatal Error, 当出现这种错误的时候,程序就无法继续执行下去了 
错误示例: 
- // Fatal error: Call to undefined function hpinfo() in /tmp/php/index.php on line 5 
 - hpinfo();  //E_ERROR 
 
  
注意,如果有未被捕获的异常,也是会触发这个级别的。 
- // Fatal error: Uncaught exception 'Exception' with message 'test exception' in /tmp/php/index.php:5 Stack trace: #0 {main} thrown in /tmp/php/index.php on line 5 
 - throw new Exception("test exception"); 
 
  
这种错误只是警告,不会终止脚本,程序还会继续进行,显示的错误信息是Warning。比如include一个不存在的文件。 
- //Warning: include(a.php): failed to open stream: No such file or directory in /tmp/php/index.php on line 7 
 - //Warning: include(): Failed opening 'a.php' for inclusion (include_path='.:/usr/share/pear:/usr/share/php') in /tmp/php/index.php on line 7 
 - include("a.php"); //E_WARNING 
 
  
E_NOTICE 
这种错误程度更为轻微一些,提示你这个地方不应该这么写。这个也是运行时错误,这个错误的代码可能在其他地方没有问题,只是在当前上下文情况下出现了问题。 
比如$b变量不存在,我们把它赋值给另外一个变量 
- //Notice: Undefined variable: b in /tmp/php/index.php on line 9 
 - $a = $b; //E_NOTICE 
 
  
E_PARSE 
这个错误是编译时候发生的,在编译期发现语法错误,不能进行语法分析。 
比如下面的z没有设置为变量。 
- // Parse error: syntax error, unexpected '=' in /tmp/php/index.php on line 20 
 - z=1; // E_PARSE 
 
  
E_STRICT 
这个错误是PHP5之后引入的,你的代码可以运行,但是不是PHP建议的写法。 
比如在函数形参传递++符号 
- // Strict Standards: Only variables should be passed by reference in /tmp/php/index.php on line 17  
 - function change (&$var) { 
 -   $var += 10; 
 - } 
 - $var = 1; 
 - change(++$var); 
 - // E_STRICT 
 
  
E_RECOVERABLE_ERROR 
这个级别其实是ERROR级别的,但是它是期望被捕获的,如果没有被错误处理捕获,表现和E_ERROR是一样的。 
经常出现在形参定义了类型,但调用的时候传入了错误类型。它的错误提醒也比E_ERROR的fatal error前面多了一个Catachable的字样。 
 
- //Catchable fatal error: Argument 1 passed to testCall() must be an instance of A, instance of B given, called in /tmp/php/index.php on line 37 and defined in /tmp/php/index.php on line 33 
 - class A { 
 - } 
 -  
 - class B { 
 - } 
 -  
 - function testCall(A $a) { 
 - } 
 -  
 - $b = new B(); 
 - testCall($b); 
 
  
E_DEPRECATED 
这个错误表示你用了一个旧版本的函数,而这个函数后期版本可能被禁用或者不维护了。 
比如curl的CURLOPT_POSTFIELDS使用@FILENAME来上传文件的方法 
- // Deprecated: curl_setopt(): The usage of the @filename API for file uploading is deprecated. Please use the CURLFile class instead in /tmp/php/index.php on line 42 
 -  
 - $ch = curl_init("http://www.remotesite.com/upload.php"); curl_setopt($ch, CURLOPT_POSTFIELDS, array('fileupload' => '@'. "test")); 
 
  
E_CORE_ERROR, E_CORE_WARNING 
这两个错误是由PHP的引擎产生的,在PHP初始化过程中发生。 
E_COMPILE_ERROR, E_COMPILE_WARNING 
这两个错误是由PHP引擎产生的,在编译过程中发生。 
E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE, E_USER_DEPRECATED, 
                                                (编辑:滁州站长网) 
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! 
                     |