is_a(object $object, string $class_name, bool $allow_string = false): bool
$object The object to be checked
$class_name The class name as a string
Returns true if the object is an instance of the class or its subclass; otherwise, returns false
Example:
class Animal {}
class Dog extends Animal {}
<p>$dog = new Dog();</p>
<p>var_dump(is_a($dog, 'Dog')); // true<br>
var_dump(is_a($dog, 'Animal')); // true, because Dog extends Animal<br>
var_dump(is_a($dog, 'Cat')); // false<br>
Suppose we want to check if an object belongs to any of the classes Dog, Cat, or Bird. The most common way is:
if (is_a($obj, 'Dog') || is_a($obj, 'Cat') || is_a($obj, 'Bird')) {
// Object belongs to one of these three classes
}
If there are many classes to check, this approach becomes inconvenient and hard to maintain.
We can encapsulate a function that takes an object and an array of class names, returning whether the object belongs to any of these classes.
function is_a_any($object, array $classNames): bool {
foreach ($classNames as $className) {
if (is_a($object, $className)) {
return true;
}
}
return false;
}
Usage example:
$classes = ['Dog', 'Cat', 'Bird'];
<p>if (is_a_any($obj, $classes)) {<br>
echo "Object belongs to one of the classes";<br>
} else {<br>
echo "Object does not belong to these classes";<br>
}<br>
PHP class names are case-insensitive, but for rigor, we could normalize case during checks:
function is_a_any($object, array $classNames): bool {
foreach ($classNames as $className) {
if (is_a($object, $className)) {
return true;
}
}
return false;
}
In fact, is_a() is already case-insensitive, so no extra handling is needed.
If you want to check whether an object implements an interface, is_a() also works.
<?php
<p>class Dog {}<br>
class Cat {}<br>
class Bird {}</p>
<p>class Bulldog extends Dog {}</p>
<p>function is_a_any($object, array $classNames): bool {<br>
foreach ($classNames as $className) {<br>
if (is_a($object, $className)) {<br>
return true;<br>
}<br>
}<br>
return false;<br>
}</p>
<p>$bulldog = new Bulldog();</p>
<p>$checkClasses = ['Cat', 'Bird', 'Dog'];</p>
<p>if (is_a_any($bulldog, $checkClasses)) {<br>
echo "Object belongs to one of the specified classes";<br>
} else {<br>
echo "Object does not belong to these classes";<br>
}<br>
Output:
Object belongs to one of the specified classes
Because Bulldog is a subclass of Dog.
is_a() is used to check if an object belongs to a class or its subclass
For multiple class checks, use a loop to encapsulate the function is_a_any() with an array of class names
The function is flexible, concise, and easy to maintain and extend
Encapsulating such a function makes the code more elegant and easier to understand, a useful technique commonly applied in development.