dongquan8753 2017-12-09 12:21
浏览 253
已采纳

设置自定义异常处理程序时,error_get_last()在PHP 7中返回NULL

Ok, this took some time to break it down. Here it is:

There is an included faulty script which is the following for the remainder of this post:

faulty.php

<?php
$a = 4 // missing semicolon
$b = 2;

Then consider the following script for handling the error. Note, that the custom exception handler is initially not registered.

script.php

<?php

// disable default display of errors
ini_set('display_errors', 0);

// register functions
#set_exception_handler('catchException'); // initially not set
register_shutdown_function('catchError');

// define error function
function catchError(){

  echo "PHP version: ".phpversion();

  if(is_null(error_get_last())) echo "<h1>No errors fetched!</h1>";
  else                          echo "<h1>Error fetched:</h1>";

  var_dump(error_get_last());

}

// define exception function (not used in all examples)
function catchException(){}

// include faulty script
include("D:/temp/faulty.php");

Result with no custom exception handler

The results for PHP 5 and 7 are identical. The error_get_last() function returns the last ocurred error (Screenshot).

Result with custom error handler

Now we set a custom function uncommenting the line

set_exception_handler('catchException');

This will work fine in PHP 5, however in PHP 7 the error_get_last() function returns NULL (Screenshot).

Question

Why is this? Especially confusing as the custom exception handler is empty, e.g. not "successfully handling" the error.

How to prevent this?

All the best and thanks for hints!

Update: problem and solution

The thing (not really a problem) is that PHP 7 throws an exception of type ParseError rather then producing an error. Thus, it is best handled with an exception handler. Make a nice exception handler to handle the exception well:

function catchException($e){

  echo "<h1>".get_class($e)."</h1>";
  echo $e->getMessage()."<br>";

}
  • 写回答

1条回答 默认 最新

  • dongzhuo7291 2017-12-09 12:29
    关注

    PHP 7 throws a ParseError exception instead of triggering an error of type E_PARSE. The default exception handler seems to trigger an error if an uncaught exception is encountered. However if you replace it with set_exception_handler() it no longer happens unless you do it yourself.

    See PHP docs:

    PHP 7 changes how most errors are reported by PHP. Instead of reporting errors through the traditional error reporting mechanism used by PHP 5, most errors are now reported by throwing Error exceptions.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥15 QT6颜色选择对话框显示不完整
  • ¥20 能提供一下思路或者代码吗
  • ¥15 用twincat控制!
  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥15 DS18B20内部ADC模数转换器