Object type information

bool is_subclass_of ( mixed object, string class_name)

As you can see, inheriting from class to class is an incredibly 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 can be used like an operator. Instance of will return true if the object on the left-hand side is of the same class or a descendant of the class given on the right-hand side. 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 is a descendant of the dog class.

Author's Note: Java programmers will be happy to know that instanceof is the same old friend they've grown used to over the years. It is a great keyword to keep to hand, as any Java veteran will tell you, and you will almost certainly find yourself using it quite often in your scripts.

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() function. This takes an object as its first parameter (or a string containing a class name), 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:

<?php
    
class dog { }
    class
poodle extends dog { }
    
$poppy = new poodle();
    print (int)(
$poppy instanceof poodle);
    print
"\n";
    print (int)
is_subclass_of($poppy, "poodle");
?>

That should output a 1 then a 0. Typecasting to int is used because boolean false is printed out as "" (blank), but by typecasting to an integer this becomes 0. As you can see, using instanceof reports true that $poppy is either a poodle or a dog, whereas is_subclass_of() reports false because $poppy is not descended from the class "poodle" - it is a poodle.

Author's Note: You can also use the instanceof keyword to see whether an object implements an interface.

 

Next chapter: Class type hints >>

Previous chapter: Iterating through object variables

Jump to:

 

Home: Table of Contents

Follow us on Identi.ca or Twitter

Username:   Password:
Create Account | About TuxRadar