PHP - Class/Object is_a() Function



The PHP Class/Object is_a() function is used to find whether an object or class belongs to a certain class or a subclass. It returns true when the object or class is an instance and false otherwise. This function is useful for verifying types in object-oriented programming.

Syntax

Below is the syntax of the PHP Class/Object is_a() function −

bool is_a(mixed $object_or_class, string $class, bool $allow_string = false)

Parameters

Here are the parameters of the is_a() function −

  • $object_or_class − It is the object or class name you want to check.

  • $class − It is the class name.

  • $allow_string − If set to true, the function will accept class names as strings in along with objects. The default value is False.

Return Value

The is_a() function returns TRUE if object_or_class is the class object type or has class as a supertype; FALSE otherwise.

PHP Version

First introduced in core PHP 4.2.0, the is_a() function continues to function easily in PHP 5, PHP 7, and PHP 8.

Example 1

First we will show you the basic example of the PHP Class/Object is_a() function check if the object is an instance of the class Car.

<?php
   // Define class here
   class Car {}

   $myCar = new Car();
   
   if (is_a($myCar, 'Car')) {
       echo "Yes, \$myCar is an instance of Car.";
   } else {
       echo "No, \$myCar is not an instance of Car.";
   }
?>

Output

Here is the outcome of the following code −

Yes, $myCar is an instance of Car.

Example 2

In the below PHP code we will use the is_a() function and check if the object of a subclass is an instance of the parent class.

<?php
   // Define class here
   class Vehicle {}
   class Car extends Vehicle {}
   
   $myCar = new Car();
   
   if (is_a($myCar, 'Vehicle')) {
       echo "Yes, \$myCar is an instance of Vehicle.";
   } else {
       echo "No, \$myCar is not an instance of Vehicle.";
   }
?> 

Output

This will generate the below output −

Yes, $myCar is an instance of Vehicle.

Example 3

Here, the is_a() function checks a class name string instead of an object by setting the parameter $allow_string to true.

<?php
   // Define class here
   class Truck {}

   $className = 'Truck';
   
   if (is_a($className, 'Truck', true)) {
       echo "Yes, $className is a valid class name.";
   } else {
       echo "No, $className is not a valid class name.";
   }
?> 

Output

This will create the below output −

Yes, Truck is a valid class name
php_function_reference.htm
Advertisements