PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1
CHAPTER 5 ■ OBJECT TOOLS

is_callable() optionally accepts a second argument, a Boolean. If you set this to true, the function
will only check the syntax of the given method or function name and not its actual existence.
The method_exists() function requires an object (or a class name) and a method name, and returns
true if the given method exists in the object’s class.


if ( method_exists( $product, $method ) ) {
print $product->$method(); // invoke the method
}


■Caution Remember that the fact that a method exists does not mean that it will be callable. method_exists()


returns true for private and protected methods as well as for public ones.


Learning About Properties


Just as you can query the methods of a class, so can you query its fields. The get_class_vars() function
requires a class name and returns an associative array. The returned array contains field names as its
keys and field values as its values. Let’s apply this test to the CdProduct object. For the purposes of
illustration, we add a public property to the class: CdProduct::$coverUrl.


print_r( get_class_vars( 'CdProduct' ) );


Only the public property is shown:

Array
(
[coverUrl] =>
)


Learning About Inheritance


The class functions also allow us to chart inheritance relationships. We can find the parent of a class, for
example, with get_parent_class(). This function requires either an object or a class name, and it returns
the name of the superclass, if any. If no such class exists, that is, if the class we are testing does not have
a parent, then the function returns false.


print get_parent_class( 'CdProduct' );


As you might expect, this yields the parent class: ShopProduct.
We can also test whether a class is a descendent of another using the is_subclass_of() function.
This requires a child object and the name of the parent class. The function returns true if the second
argument is a superclass of the first argument.


$product = getProduct(); // acquire an object
if ( is_subclass_of( $product, 'ShopProduct' ) ) {
print "CdProduct is a subclass of ShopProduct\n";
}

Free download pdf