SoFunction
Updated on 2025-04-08

Section 11 Overload [11]


PHP4 already has overloaded syntax to establish mappings to external object models, just like Java and COM. PHP5 brings powerful object-oriented overloading, allowing programmers to establish customized behaviors to access properties and call methods.

Overloading can be done through several special methods __get, __set, and __call. PHP will call these methods when the Zend engine attempts to access a member and is not found.

In Example 6.14, __get and __set replace all access to the array of attribute variables. If necessary, you can implement any type of filtering you want. For example, a script can prohibit setting property values, starting with a certain prefix or containing a certain type of value.

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 the value of __call is passed to the undefined method by PHP.

Listing 6.14 User-level overloading
<?php
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()<br>n");
print("Arguments: ");
print_r($args);

return(TRUE);
}
}
$o = new Overloader();

//invoke __set() Assign a value to a non-existent attribute variable and activate __set()
$o->dynaProp = "Dynamic Content";

//invoke __get() Activate __get()
print($o->dynaProp . "<br>n");

//invoke __call() Activate __call()
$o->dynaMethod("Leon", "Zeev");
?>