SoFunction
Updated on 2025-04-07

Section 11 - Overload

/*
+-------------------------------------------------------------------------------+
| = This article is read by Haohappy<<Core PHP Programming>>
| =Notes from the chapter Classes and Objects
| = Translation as the main + personal experience
| = To avoid unnecessary troubles that may occur, please do not reprint, thank you
| = Criticism and correction are welcome, and I hope to make progress with all PHP enthusiasts!
| = PHP5 Research Center:/haohappy2004
+-------------------------------------------------------------------------------+
*/
Section 11 - Overload
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 performed through several special methods __get, __set, and __call. When the Zend engine attempts to access a member and is not found, PHP will call these methods.
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, using a certain prefix or containing a certain type of value at the beginning.
The __call method explains how you call an undefined method. When you call an undefined method, the method name and parameters received by the method will be passed to the __call method, and the PHP passes the value of __call to return to the undefined method.
Listing 6.14 User-level overloading
Copy the codeThe code is as follows:
<?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");  
?>