Object Type Information

Inheriting from class to class is a powerful way to build up functionality in your scripts. However, very often it is easy to get lost with your inheritance—how can you tell what class a given object is?

PHP comes to the rescue with a special keyword, instanceof, which is an operator. Instanceof will return true if the object on the lefthand side is of the same class, or a descendant of, the class given on the righthand side. You can also use the instanceof keyword to see whether an object implements an interface. For example, given the code $poppy = new Poodle;:

    if ($poppy instanceof poodle) { }
    if ($poppy instanceof dog) { }

Both of those if statements would evaluate to be true, because $poppy is an object of the Poodle class and also a descendant of the Dog class.

Tip

Java programmers will be happy to know that instanceof is the same old friend they've grown used to over the years.

If you only want to know whether an object is a descendant of a class, and not of that class itself, you can use the is_subclass_of() method. This takes an object as its first parameter, a class name string as its second parameter, and returns either true or false depending on whether the first parameter is descended from the class specified in the second parameter.

Understanding the difference between instanceof and is_subclass_of() is crucial—this script should make it clear:

 class Dog { } class Poodle extends Dog { } $poppy = new Poodle(); print (int)($poppy instanceof Poodle); ...

Get PHP in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.