Page 228 - Beginning PHP 5.3
P. 228
Part II: Learning the Language
The __call() method is where the meat of the class lies:
public function __call( $methodName, $arguments ) {
if ( in_array( $methodName, CleverString::$_allowedFunctions ) ) {
array_unshift( $arguments, $this- > _theString );
return call_user_func_array( $methodName, $arguments );
} else {
die ( “ < p > Method ‘CleverString::$methodName’ doesn’t exist < /p > ” );
}
}
First, the method stores the name of the method that was called in a $methodName parameter, and the
array containing any passed arguments is stored in the $arguments parameter.
Next the method checks that $methodName is contained in the CleverString::$_allowedFunctions
array. This is a private static property, created at the start of the class, that contains the allowed
method names:
private static $_allowedFunctions = array( “strlen”, “strtoupper”, “strpos” );
If $methodName is not one of these three values, the function terminates the script with an error
message:
die ( “ < p > Method ‘CleverString::$methodName’ doesn’t exist < /p > ” );
This ensures that only the string functions strlen() , strtoupper() , and strpos() can be called via
the class. In reality, most of PHP ’ s built - in string functions could be called this way, but for this simple
example, the script allows only these three functions to be called. Generally speaking, for security
reasons it ’ s a good idea to check arguments of this nature against a list of allowed values.
Once $methodName has been successfully validated, the method adds the object ’ s stored string value,
$this - > _theString , to the start of the $arguments array:
array_unshift( $arguments, $this-> _theString );
This is because most built - in string functions — including the three that this class is capable of calling
— expect the string to operate on to be the first argument that is passed to them.
Finally, the __call() method is ready to call the appropriate string function. It does this using the
PHP function call_user_func_array() , which expects the function name as the first argument, and
the argument list — as an array — as the second argument. The __call() method then returns the
return value from the string function back to the method ’ s calling code:
return call_user_func_array( $methodName, $arguments );
The script then tests the class by creating a new CleverString object, setting its string value to
“Hello!” , displaying the stored string value, and calling various methods to operate on the string:
$myString = new CleverString;
$myString- > setString( “Hello!” );
echo “ < p > The string is: “ . $myString- > getString() . “ < /p > ”;
echo “ < p > The length of the string is: “ . $myString- > strlen() . “ < /p > ”;
echo “ < p > The string in uppercase letters is: “ . $myString- > strtoupper() .
“ < /p > ”;
190
9/21/09 9:03:39 AM
c08.indd 190 9/21/09 9:03:39 AM
c08.indd 190