PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1

CHAPTER 5 ■ OBJECT TOOLS


Learning About Methods


You can acquire a list of all the methods in a class using the get_class_methods() function. This requires
a class name and returns an array containing the names of all the methods in the class.


print_r( get_class_methods( 'CdProduct' ) );


Assuming the CdProduct class exists, you might see something like this:

Array
(
[0] => __construct
[1] => getPlayLength
[2] => getSummaryLine
[3] => getProducerFirstName
[4] => getProducerMainName
[5] => setDiscount
[6] => getDiscount
[7] => getTitle
[8] => getPrice
[9] => getProducer
)


In the example, I pass a class name to get_class_methods() and dump the returned array with the
print_r() function. I could alternatively have passed an object to get_class_methods() with the same
result.
Unless you’re running a very early version of PHP 5, only the names of public methods will be
included in the returned list.
As you have seen, you can store a method name in a string variable and invoke it dynamically
together with an object, like this:


$product = getProduct(); // acquire an object
$method = "getTitle"; // define a method name
print $product->$method(); // invoke the method


Of course, this can be dangerous. What happens if the method does not exist? As you might expect,
your script will fail with an error. You have already encountered one way of testing that a method exists:


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


I check that the method name exists in the array returned by get_class_methods() before invoking
it. PHP provides more specialized tools for this purpose. You can check method names to some extent
with the two functions is_callable() and method_exists(). is_callable() is the more sophisticated of
the two functions. It accepts a string variable representing a function name as its first argument and
returns true if the function exists and can be called. To apply the same test to a method, you should pass
it an array in place of the function name. The array must contain an object or class name as its first
element and the method name to check as its second element. The function will return true if the
method exists in the class.


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

Free download pdf