php

How to check if an object is an instance of a specific class in PHP?

The following methods and operators are useful to determine whether a particular variable is an object of a specified class:

  • $var instanceof TestClass: The operator “instanceof” returns true if the variable $var is an object of the specified class (here is: “TestClass”).
  • get_class($var): Returns the name of the class from $var, which can be compared with the desired class name.
  • is_object($var): Checks whether the variable $var is an object.

In addition, the expected classes can be specified directly in parameters of functions. If a variable is not an instance of the class, an error is automatically generated.

// $var must be an object of the class TestClass
// (Classes derived from "TestClass" are also allowed.)
function myFunction(TestClass $var) {
    // ...
}

 

 

Example 1: Check with instanceof

In this example a short function named “rateAnimal($obj)” is written, which evaluates a given animal. Therefore a class “Animal” is created from which the classes “dog”, “cat” and “mouse” are derived. The function has only ratings for the classes “Cat” and “Dog”, so it returns only the message “Unknown animal passed” for all other animals. If no animal is passed, the function complains with the error “No animal passed”.

<?php
    class Animal { }
    class Cat extends Animal { }
    class Dog extends Animal { }
    class Mouse extends Animal { }
    class Bird { }
 
    function rateAnimal($obj) 
    {
        if ($obj instanceof Cat) 
        {
            return "I'am a Cat! \n";
        }
        else if ($obj instanceof Dog) 
        {
            return "I'am a Dog! \n";
        }
        else if ($obj instanceof Animal) 
        {
            return "I'am an Animal. \n";
        }
        else 
        {
            return "This animal not known! \n";
        }
    }
 
    echo('Cat: '.rateAnimal(new Cat()));
    echo('Dog: '.rateAnimal(new Dog()));
    echo('Mouse: '.rateAnimal(new Mouse()));
    echo('Bird: '.rateAnimal(new Bird()));
?>

Output:

Cat: I'am a Cat! 
Dog: I'am a Dog! 
Mouse: I'am an Animal. 
Bird: This animal not known!
PHP MCQ - Multiple Choice Questions and AnswersPHP Questions and Answers – Object-Oriented OOP – Part 1This collection of PHP Multiple Choice Questions and Answers (MCQs): Quizzes & Practice Tests with Answer focuses on “Object-Oriented OOP”.   1. The concept of…Read More
 

Example 2: Check with get_class()

Again the same example, but this time the check is done with get_class(). The check with get_class() is less flexible than instanceof. While instanceof also checks for parent classes (for example, for “Dog” the parent class is “Animal”), this is not possible with get_class(). Therefore the result of the function is modified here and does not return a matching error message when an unknown animal is passed.

<?php
    class Animal { }
    class Cat extends Animal { }
    class Dog extends Animal { }
    class Mouse extends Animal { }
    class Bird { }
 
     function rateAnimal($obj) 
     {
        if (!is_object($obj)) 
        {
            echo("It's not an object! \n");
        } 
        else 
        {
            if (get_class($obj) === 'Cat') 
            {
                return "I'am a Cat! \n";
            } 
            else if (get_class($obj) === 'Dog') 
            {
                return "I'am a Dog! \n";
            } 
            else 
            {
                return "It's not a dog or cat! \n";
            }
        }
    }
 
    echo('Cat: '.rateAnimal(new Cat()));
    echo('Dog: '.rateAnimal(new Dog()));
    echo('Mouse: '.rateAnimal(new Mouse()));
    echo('Bird: '.rateAnimal(new Bird()));
?>

Output:

Cat: I'am a Cat! 
Dog: I'am a Dog!
Mouse: It's not a dog or cat! 
Bird: It's not a dog or cat!
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *