Page 226 - Beginning PHP 5.3
P. 226
Part II: Learning the Language
Try It Out Create a Wrapper String Class
The following example shows how you can use __call() to create a wrapper class. In this case, the
class provides an object - oriented interface to three of PHP ’ s built - in string functions. Save the script as
clever_string.php in your document root folder, then run it in your Web browser:
< !DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd” >
< html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en” lang=”en” >
< head >
< title > Creating a Wrapper Class with __call() < /title >
< link rel=”stylesheet” type=”text/css” href=”common.css” / >
< /head >
< body >
< h1 > Creating a Wrapper Class with __call() < /h1 >
< ?php
class CleverString {
private $_theString = “”;
private static $_allowedFunctions = array( “strlen”, “strtoupper”,
“strpos” );
public function setString( $stringVal ) {
$this- > _theString = $stringVal;
}
public function getString() {
return $this- > _theString;
}
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 > ” );
}
}
}
$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 > ”;
188
9/21/09 9:03:38 AM
c08.indd 188 9/21/09 9:03:38 AM
c08.indd 188