Search code examples
error-handlingphp-8

Shoud I use trigger_error in PHP8


I am revising a PHP project that is necessary because of a massive redesign in the database. Therefore, the project should use the latest PHP version, which at the moment of writing is version 8. I am also using an OOP approach with namespace, so the project can benefit from features like autoloading in the future.

In the new classes I wrote, I need to throw errors. But in PHP 8, there are so many ways to do this. I could use trigger_error or exceptions or the error class and its specific variants like value error. Now I am unsure which to choose. Currently I have a mixture of exceptions and trigger_error in the code.

I have a custom handler defined for both exception and "old" errors, which writes the errors to a log file so I can fix them (if possible).

So what should I use to write a future-proof code? Unfortunately I couldn't find anything in the PHP docs about this. Also my web research didn't bring any useful result unfortunately. Is there a best approach rule?


Solution

  • I'm not a PHP expert.

    However my little observation is that latest PHP versions tend to be more OOP. PHP now supports many OOP features you will find in any other fully OOP languages like C# or Java. We can see that many PHP functions now throw exceptions, and with the introduction of Exception and Error in PHP 7 and ValueError in PHP 8 you are likely to encounter and have to deal with exceptions than the infamous false and null.

    A very small list of PHP features that now throw excptions (with versions next to them):

    • Constructors of internal classes will now always throw an exception (PHP 7)
    • Calling a function with less arguments than mandatory declared ones throws exception (PHP 7.1)
    • 1 + "a" throws TypeError (PHP 8)
    • explode throws ValueError when separator parameter is given an empty string (PHP 8)
    • mb_ord throws ValueError when $string argument is given an empty string (PHP 8)
    • MySQLi the default error handling mode has been changed from "silent" to "exceptions" (PHP 8.1)

    And many more will throw an instance of Error or exception instead of resulting in a fatal error.

    Conclusion

    Throw exceptions instead of using trigger_error.