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.
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
:
$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:
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
.