# Constructors of Internal Classes

> Section in “New and Extended Functionality › Error Handling” of the book [PHP 7 Explained](https://php7explained.com/) by Sebastian Bergmann and Stefan Priebsch, published by thePHP.cc. The book covers PHP 7.0 to 7.4 and was last updated in November 2020. HTML version: <https://php7explained.com/new-and-extended-functionality/error-handling/constructors-of-internal-classes/>

Before PHP 7 several internal classes that ship with PHP exhibit a quite surprising behavior when invalid arguments are passed to their constructor. Rather than getting an exception as would be expected, PHP merrily emitted a warning and either returned `null` or otherwise continued with a broken instance of that class.

The following classes used to return `null` for invalid constructor arguments:

- `finfo`
- `PDO`
- `Collator`
- `IntlDateFormatter`
- `MessageFormatter`
- `NumberFormatter`
- `ResourceBundle`
- `IntlRuleBasedBreakIterator`

The best way to handle this in PHP 5 was by registering an explicit error handler converting the emitted warning into an exception.

``` php
set_error_handler(
    function($severity, $message, $file, $line, array $context) {
        throw new ErrorException(
            $message, 0, $severity, $file, $line
        );
    }
);
```

If that was not possible the only alternative was an explicit check for `null`:

``` php
$info = new finfo('invalid');
if ($info === null) {
   // error handling goes here
}
```

As of PHP 7, this will no longer work because an exception or error is thrown, which can be caught using a `catch` statement. For `finfo` and the example above, the adjusted code would look like this:

``` php
try {
    $info = new finfo('invalid');
} catch (TypeError $e) {
   // error handling goes here
}
```

In some other cases, PHP used to only emit a warning but continue with an unusable instance of the respective class. The following classes used to show this kind of behavior:

- `UConverter`
- `SplFixedArray`
- `ReflectionFunction`
- `ReflectionParameter`
- `ReflectionMethod`
- `ReflectionProperty`
- `ReflectionExtension`
- `ReflectionZendExtension`
- `Phar`
- `PharData`
- `PharFileInfo`

As neither of these classes – after emitting the warning – provided any additional means of noticing that the construction did not succeed, the only way to handle potential problems before PHP 7, again, is a custom error handler. After converting the warning into an `ErrorException`, it can then be thrown and caught using the usual `try` and `catch`.

---

Previous: [Errors in Extensions](https://php7explained.com/new-and-extended-functionality/error-handling/errors-in-extensions/index.html.md) | Next: [Better syslog support with error_log](https://php7explained.com/new-and-extended-functionality/error-handling/better-syslog-support-with-error_log/index.html.md)
