Too few arguments to function exception_error_handler() - PHP8

Viewed 1150

How the title said, that error occurs to me. I search the internet and find that https://github.com/processwire/processwire-issues/issues/1286#issuecomment-738880424

Original code:

function exception_error_handler($errno, $errstr, $errfile, $errline, $errcontext) {
}

I just change the last parameter and make it optional like that:

function exception_error_handler($errno, $errstr, $errfile, $errline, $errcontext=[]) {
}

Does anyone know why this parameter became optional?

1 Answers

There is some confusion here about what is optional and why.

The function you are defining is a callback which will be called by PHP with certain arguments, which are documented in the manual. (Note that at the time of asking, that page used different wording; after writing this answer, I submitted a patch updating it for PHP 8.0 and hopefully making it clearer).

Older versions of PHP pass 5 parameters to the callback, with the 5th parameter receiving, according to the documentation:

An array of every variable that existed in the scope the error was triggered in.

This causes a lot of odd behaviour and prevents certain optimisations in the engine, so in PHP 7.2, it was encouraged to remove usage of this parameter. In PHP 8.0, the parameter is no longer passed - that is, PHP now calls your callback with only 4 parameters.

This parameter has always been "optional", in the sense that it is safe not to list it in the signature at all. A callback such as this, with 4 parameters, will be accepted by all versions of PHP:

function my_error_handler($errno, $errstr, $errfile, $errline) {
   // ...
}

The correct solution is to remove that parameter from your function completely, if:

  • you are writing code which will only run on PHP 8.0 and higher; or
  • you never actually use that parameter in your function

If the implementation was actually relying on that parameter, other changes will be needed. You might conceivably want to include the parameter with a default value (making it "optional" in a different sense) and use it when passed on older versions of PHP:

function my_error_handler($errno, $errstr, $errfile, $errline, $errcontext=[]) {
   // $errcontext will be populated on older PHP versions, 
   // but will always be an empty array on PHP 8.0 or above
   // Any functionality using it will become useless in future
}

However, you're probably better off simply removing the code that relied on it, and finding a more future-proof solution.

Related