Skip to Main Content
PHP in a Nutshell
book

PHP in a Nutshell

by Paul Hudson
October 2005
Intermediate to advanced content levelIntermediate to advanced
372 pages
11h 35m
English
O'Reilly Media, Inc.
Content preview from PHP in a Nutshell

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); ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 0596100671Errata Page