In PHP, the is_a function checks whether an object belongs to a given class or to a class which inherits from it. A class name can be passed as a string instead of an object, but only when the third argument, $allow_string, is set to true. That argument defaults to false.
Since PHP 8.6, calling is_a with a string while $allow_string is false is deprecated. Such a call always returns false, even when the classes are related:
<?php
$class = 'RuntimeException';
var_dump(is_a($class, Exception::class));
Output:
Deprecated: Calling is_a() with a string when $allow_string is false in main.php on line 5
bool(false)
The RuntimeException class extends Exception, so the expected result is true. Because $allow_string is false, the function does not treat RuntimeException as a class name, and the check silently fails.
The example can be fixed by passing true as the third argument:
<?php
$class = 'RuntimeException';
var_dump(is_a($class, Exception::class, true));
Output:
bool(true)
The deprecation is gone and the result is correct. An object passed as the first argument is not affected, because $allow_string applies to strings only.
The is_subclass_of function carries the same deprecation, but its $allow_string argument defaults to true. A class name is therefore accepted by default, and the deprecation appears only when false is passed explicitly, which is rare.
Leave a Comment
Cancel reply