In PHP, the is_a() function is used to detect whether an object belongs to a certain class or subclass of a class. The syntax is as follows:
is_a(object $object, string $class_name, bool $allow_string = false): bool
Among them, the first parameter must be the object or object name, and the second parameter is the class name. If the order of these two parameters is reversed, what will the code have? This article will use examples to analyze the performance and potential risks of is_a() when using the wrong parameter order.
Suppose there are two categories:
class Animal {}
class Dog extends Animal {}
$dog = new Dog();
var_dump(is_a($dog, 'Animal')); // true,Dog yes Animal Subclasses of
var_dump(is_a($dog, 'Dog')); // true,$dog yes Dog Examples
In this code, is_a($dog, 'Animal') will return true , indicating that the $dog object does belong to the Animal class or its subclass.
If you write the parameter order in reverse, for example:
var_dump(is_a('Animal', $dog)); // Error demonstration
What happens at this time? Let's analyze:
The first argument is the string 'Animal' , not the object.
The second parameter is object $dog , not class name string.
According to the definition of is_a() , the function expects that the first parameter is an object and the second parameter is a string class name, and the order is reversed to cause type mismatch.
PHP 7.2 and above will throw warnings or errors , such as:
Warning: is_a() expects parameter 1 to be object, string given
The function returns false and cannot be correctly judged.
The code logic fails, resulting in a failure in judgment.
Sample code:
$dog = new Dog();
var_dump(is_a('Animal', $dog)); // false,And a warning
is_a() allows the third parameter $allow_string to be set to true to support the first parameter passing into the class name string instead of the object:
var_dump(is_a('Dog', 'Animal', true)); // true,Judgment Dog yes否继承 Animal
But even in this case, the second parameter must still be the string class name, and the reverse order still errors:
var_dump(is_a('Animal', $dog, true)); // Still wrong,Parameter order inverted
The first parameter of the is_a() function must be an object (or when $allow_string is true , it is a class name string), and the second parameter must be a class name string.
Reversing the parameter order will cause type mismatch, PHP will alert and return false , and the judgment will be invalid.
Special attention should be paid to the parameter order in development to avoid logical vulnerabilities that are difficult to discover due to parameter transfer errors.