PHP4 already has overloading syntax to establish mappings to external object models, just like Java and COM. PHP5 brings powerful object-oriented overloading, allowing programmers to create custom behaviors to access properties and call methods .
Overloading can be performed through several special methods __get, __set, and __call. When the Zend engine tries to access a member and cannot find it, PHP will call these methods.
In Example 6.14, __get and __set replace all accesses to the attribute variable array. If necessary, you can implement any kind of filtering you want. For example, the script can disable setting attribute values, start with a certain prefix or include A value of a certain type. The
__call method explains how you call an undefined method. When you call an undefined method, the method name and the parameters received by the method will be passed to the __call method, and PHP passes the __call Value returned to undefined method.
Listing 6.14 User-level overloading
class Overloader
{
private $properties = array();
function __get($property_name)
{
if(isset($this- >properties[$property_name]))
{
return($this->properties[$property_name]);
}
else
{
return(NULL);
}
}
function __set($property_name, $value)
{
$this->properties[$property_name] = $value;
}
function __call($function_name, $args)
{
print("Invoking $function_name()
n");
print("Arguments: ");
print_r($args);
return(TRUE);
}
}
$o = new Overloader();
//invoke __set() gives a To assign a value to a non-existent attribute variable, activate __set()
$o->dynaProp = "Dynamic Content";
//invoke __get() activate __get()
print($ o->dynaProp . "
n");
//invoke __call() Activate __call()
$o->dynaMethod("Leon", "Zeev") ;
?>