Create a Wrapper Class with __call() in PHP
Description
The following code shows how to create a Wrapper Class with __call().
Example
// w w w .ja va2s . c o m
<?php
class MyString {
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, MyString::$_allowedFunctions ) ) {
array_unshift( $arguments, $this->_theString );
return call_user_func_array( $methodName, $arguments );
} else {
die ( "<p>Method 'MyString::$methodName' doesn't exist</p>" );
}
}
}
$myString = new MyString;
$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>";
echo "<p>The letter 'e' occurs at position: " . $myString->strpos( "e" ) . "</p>";
$myString->madeUpMethod();
?>
The code above generates the following result.