PHP - Determining an Object's Class

Introduction

To explicitly check the class of a particular object that you're working with.

To find out the class of an object, you can use PHP's built-in get_class() function, as follows:

Demo

<?php

        class MyClass {
        }/*from   ww  w .j  a v a  2 s.c o  m*/

        $obj = new MyClass();
        echo get_class($obj); // Displays"MyClass"
?>

Result

get_class() can find out exactly which class an object belongs to.

It's more useful to know if an object is descended from a given class.

Demo

<?php
        class Fruit {
        }// ww  w.  ja v  a  2s.com

        class SoftFruit extends Fruit {
        }

        class HardFruit extends Fruit {
        }

        function eatSomeFruit(array $fruitToEat) {
          foreach($fruitToEat as $itemOfFruit) {
            if (get_class($itemOfFruit) =="SoftFruit"|| get_class($itemOfFruit) =="HardFruit") {
              echo "Eating the fruit-yummy! \n";
            }
          }
        }

        $banana = new SoftFruit();
        $apple = new HardFruit();
        eatSomeFruit(array($banana, $apple));
?>

Result

PHP provides a useful instanceof operator, which you can use as follows:

if($object instanceof ClassName) {...

If $object 's class is ClassName, or if $object 's class is descended from ClassName, then instanceof returns true.

Otherwise, it returns false.

So you can now rewrite the preceding eatSomeFruit() function in a more elegant fashion:

<?php

        function eatSomeFruit(array $fruitToEat) {
          foreach($fruitToEat as $itemOfFruit) {

            if ($itemOfFruit instanceof Fruit) {

              echo "Eating the fruit-yummy! \n";
            }
          }
        }
?>

Related Topic