PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1
CHAPTER 5 ■ OBJECT TOOLS

Learning About an Object or Class


As you know, you can constrain the object types of method arguments using class type hinting. Even
with this tool, we can’t always be certain of an object’s type. At the time of this writing, PHP does not
allow you to constrain class type returned from a method or function, though this is apparently due for
inclusion at a later date.
There are a number of basic tools available to check the type of an object. First of all, you can check
the class of an object with the get_class() function. This accepts any object as an argument and returns
its class name as a string.


$product = getProduct();
if ( get_class( $product ) == 'CdProduct' ) {
print "\$product is a CdProduct object\n";
}


In the fragment I acquire something from the getProduct() function. To be absolutely certain that it
is a CdProduct object, I use the get_class() method.


■Note I covered the CdProduct and BookProduct classes in Chapter 3: Object Basics


Here’s the getProduct() function:

function getProduct() {
return new CdProduct( "Exile on Coldharbour Lane",
"The", "Alabama 3", 10.99, 60.33 );
}


getProduct() simply instantiates and returns a CdProduct object. I will make good use of this
function in this section.
The get_class() function is a very specific tool. You often want a more general confirmation of a
class’s type. You may want to know that an object belongs to the ShopProduct family, but you don’t care
whether its actual class is BookProduct or CdProduct. To this end, PHP provides the instanceof operator.


■Note PHP 4 did not support instanceof. Instead, it provided the is_a() function which was deprecated in PHP


5.0 deprecated. As of PHP 5.3 it is_a() no longer deprecated.


The instanceof operator works with two operands, the object to test on the left of the keyword and
the class or interface name on the right. It resolves to true if the object is an instance of the given type.


$product = getProduct();
if ( $product instanceof ShopProduct ) {
print "\$product is a ShopProduct object\n";
}

Free download pdf