get_class: Disallow "null" Value
As of PHP 7.2.0, providing null to get_class()
inside a class is no longer allowed. It will emit a warning and return false:
class MyClass {
public function __construct() {
get_class(null);
}
}
new MyClass();
As of PHP 8.0.0, warnings from this function are converted various Error
being thrown:
// Cannot use string, throws TypeError
get_class("hello");
// Cannot use null, throws TypeError
get_class(null);
// Cannot use empty outside a class, throws Error
get_class();
See execution result.
Solution
Warnings that become errors in PHP 8.0.0 should be carefully analyzed and fixed manually, since their logic was already problematic. If that is not practical, such as due to the use of variables, the less desirable solution is to wrap those statements in a try/catch:
$object = "hello";
try {
get_class($object);
} catch (TypeError $e) {}
Using null
inside a class now behaves exactly the same as no argument, therefore you can remove the argument if it is null
:
class MyClass {
public function __construct() {
$object = null;
if ($object === null) {
get_class();
}
else {
get_class($object);
}
}
}
new MyClass();
See execution result.
Errors or Warnings
- get_class(): Argument #1 ($object) must be of type object, null given
- get_class() expects parameter 1 to be object, null given