2

The next code:

$a["x"];//should trigger notice
var_dump(error_get_last());//return the error array

runs perfectly and returns an error array. but when I use set_error_handler it returns null

function _do_nothing(){}
set_error_handler('_do_nothing');

$a["x"];//should trigger notice
var_dump(error_get_last());//return null

This code works perfectly on PHP5.4 I had changed 3 month ago to PHP7 and since then I am getting nulls in error_get_last() I am using a shutdown function to check if an error has occured and if so to send it to the developer.

  1. Is there a way to make this code run in PHP7? and make error_get_last() works with set_error_handler()?
  2. Any other ideas for workaround? and make a shutdown function get the last error? I am using CodeIgniter, and prefer not to hack their internal code.
Wazime
  • 1,423
  • 1
  • 18
  • 26
  • +1 for mentioning the PHP version. This helped me understanding why my code from 4 years ago suddenly stopped working. – agoldev Dec 09 '17 at 11:10

1 Answers1

1

This is normal behavior because in your example the error is already handled by the _do_nothing() function, so the error_get_last() returns null

if you remove set_error_handler('_do_nothing') the error won't be handled anymore and you will get the last error again

function _do_nothing(){}
//set_error_handler('_do_nothing');

$a["x"];//should trigger notice
var_dump(error_get_last());//return array() "Undefined variable: a"

This behavior is the same in PHP5 as in PHP7

currarpickt
  • 2,290
  • 4
  • 24
  • 39
  • 1
    However, there is a big difference for `error_get_last()` if it is called within the error handler. If you try to catch errors (e.g. parse erorrs) with a custom function, e.g. `_do_nothing()` and call `error_get_last()` within that function `error_get_last()` would return the error in PHP 5.*. However, in PHP 7.* it would return `NULL`. – agoldev Dec 09 '17 at 11:16
  • Ok, it is more complicated. Actually the different behavior of PHP 5 and 7 requires registering a custom exception handler. I documented this here: https://stackoverflow.com/questions/47728546/error-get-last-returns-null-in-php-7-when-a-custom-exception-handler-is-set – agoldev Dec 09 '17 at 12:25