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 the example in Figure 1, __get and __set replace all Access to an array of attribute variables. If necessary, you can implement any type of filtering you want. For example, the script can disable setting attribute values, start with a certain prefix or include a certain type of value.
The __call method illustrates how you can Calling 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 value of __call back to the undefined method.
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()n");
print("Arguments: ");
print_r($args);
return(TRUE);
}
}
$o = new Overloader();
//invoke __set() assigns a value to a non-existent attribute variable and activates __set()
$o->dynaProp = "Dynamic Content";
//invoke __get() activate __get()
print($o->dynaProp . "n");
//invoke __call() activate __call()
$o->dynaMethod("Leon", "Zeev");
?>
Autoloading of classes
When you try to use an undefined class, PHP will report a fatal error. The solution is to add a class, which can be included in a file. After all, you know which class to use. However, PHP Provides an automatic loading function for classes, which can save programming time. When you try to use a class that PHP has not organized, it will look for a global function __autoload. If this function exists, PHP will call it with a parameter , the parameter is the name of the class.
Example Figure 2 illustrates how __autoload is used. It assumes that each file in the current directory corresponds to a class. When the script attempts to generate an instance of class User, PHP will execute __autoload. Script Assumptions The User class is defined in class_User.php. Regardless of whether the call is in uppercase or lowercase, PHP will return the lowercase name.
Class autoloading
<?php
//define autoload function
function __autoload($class)
{
include("class_" . ucfirst($class) . ".php");
}
//use a class that must be autoloaded
$u = new User;
$u->name = "Leon";
$u->printName();
?>