skip to Main Content

I like to use the PHP Error class to return using throw like this:

throw new Error('Some problem description');

Sadly, I have to use PHP 5.4.16 on CentOS 7.5. The Error class was introduced in PHP 7.

Is there a class that I can include which emulates the behavior of the Error class from PHP 7?

2

Answers


  1. There is no Error class in PHP 5, but this class is the same as the Exception class. If you want to generate custom errors then use Exception

    throw new Exception('Some problem description');
    

    There is no difference between Error and Exception class from a functional point of view. The only reason why we have the two is for semantic purposes. We don’t want PHP 5 code after upgrade to PHP 7 to catch Fatal errors using try() catch(Exception $e) logic.

    Login or Signup to reply.
  2. Error and Exception have the same exact signature so you can possibly use the latter:

    if (!class_exists('Error')) {
       class Error extends Exception
       {
       }
    }
    

    Demo

    Tweak for you liking. For instance, you may want to check PHP version (it’s possible that software written for PHP/5 already has a custom Error class). Of course, no native function is going to actually throw it.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search