Section 8.8. Object Type Information


8.8. 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 inheritancehow 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.

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 crucialthis script should make it clear:

     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. 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 Poodleit is a Poodle.

New versions of PHP 5 (after 5.0.2) will allow you to specify a string as parameter one of is_subclass_of( ), and check whether the class named in that string is a subclass of parameter two.




PHP in a Nutshell
Ubuntu Unleashed
ISBN: 596100671
EAN: 2147483647
Year: 2003
Pages: 249

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net