Page 254 - Beginning PHP 5.3
P. 254
Part II: Learning the Language
get_class() is useful if you want to find out exactly which class an object belongs to. However, often
it ’ s more useful to know if an object is descended from a given class. Consider the following example:
class Fruit {
}
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! < br / > ”;
}
}
}
$banana = new SoftFruit();
$apple = new HardFruit();
eatSomeFruit( array( $banana, $apple ) );
In this situation, the eatSomeFruit() function is happy to eat any fruit, soft or hard, so all it really cares
about is that the objects it is passed descend from the Fruit class. However, get_class() only returns
the specific class of an object, so eatSomeFruit() has to resort to a rather unwieldy if expression to
determine if the object it ’ s dealing with is a fruit.
Fortunately, 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:
function eatSomeFruit( array $fruitToEat ) {
foreach( $fruitToEat as $itemOfFruit ) {
if ( $itemOfFruit instanceof Fruit ) {
echo “Eating the fruit - yummy! < br / > ”;
}
}
}
216
9/21/09 9:03:48 AM
c08.indd 216
c08.indd 216 9/21/09 9:03:48 AM