0

Why does PHP have preg_last_error() instead of just throwing an error ?

Some errors you can have from executing a regex through preg_replace() are logged to PHP error file. Some others are silent and you have to check for their presence with preg_last_error(). Why is that ?

For example, an invalid REGEX is gonna send a PHP Warning. But going over the preg JIT stack limit will not, and the only way to detect this error is by checking preg_last_error() return value.

More information on the later error in this topic PHP PREG_JIT_STACKLIMIT_ERROR - inefficient regex

  • 3
    The reason is essentially historical. PHP globbed up a lot of libraries along the road, and that's why error handling is not coherent and, for that matter, even argument order is more or less random across libraries. – LSerni Jul 31 '17 at 17:51
  • What LSerni said. In a perfect world, everything that made a mistake would throw an exception, or set an error indicator in a uniform and predictable way, but we don't have that in PHP. It just keeps trying to give you an answer -- any kind of answer! See https://eev.ee/blog/2012/04/09/php-a-fractal-of-bad-design/ – Ray Paseur Jul 31 '17 at 18:05

1 Answers1

0

Historically, PHP didn't have exceptions that you could throw and catch. Core errors would crash the applications without any means to recover.

In the past, there were people who strongly believed that PHP should throw an error only when you messed up in the source code. Writing invalid regex in your code is a valid reason for an error. However, since JSON decoding can fail because of the data that is passed into it, the developer should have a way of checking for parsing errors and handling them in their application without the application crashing. This kind of error is not a developer error, but rather a data error. This justification makes some sense if we consider that JSON extension was added to PHP 5.

My guess is that if JSON extension would be added in PHP 7, then it would throw by default. PHP 7 changed the concept of PHP errors and with it people's attitude towards throwing exceptions due to invalid data. But there are still functions and APIs in PHP that don't throw errors by default.

Dharman
  • 30,962
  • 25
  • 85
  • 135