Chico3001 Chico3001 - 2 months ago 6x
PHP Question

Php 5/7 error class handling

I just recently ugraded to php7 and had my first problem when upgrading some applications using try catch

PHP7 now implements its own error class to handle the errors so the old code that i had:

try {
dispatcher::run(new request);
} catch (Exception $e) {
require_once APP_PATH . 'error.php';
$error = new error($e);

now throws an error because error class is already defined:

Cannot declare class error, because the name is already in use in [...]

Now this got solved pretty easily just renaming my error class, but it had me wonder, is there a way to extend the error class of 7, and can be both compatible with php5?



The short is you shouldn't do that, because it's a backwards incompatible change.

The long answer is yes, it's possible, but you still shouldn't do that, because it can still result in undesired behavior and still might require making changes to your existing PHP 5 implementation.

The Error class in PHP 7 implements the same Throwable interface that Exception implements. The idea was to just have a distinguishing way to identify those exceptions thrown by PHP itself and those thrown by your PHP code. So what you're doing here $error = new error($e) is basically the equivalent of $error = new Exception($e), which would be backwards compatible with PHP 5, assuming your custom Error class is compatible with the Throwable interface. Since you didn't provide your class implementation I can't say for sure, but generally speaking, if you hadn't already extended Exception in PHP 5, I somehow doubt it will be.