in PHP, we are not able to implement method overloading directly by signing different methods with the same method name, because PHP is weakData type , the signature cannot be distinguished well. However, you can implement method overloading by using the call () method in a class in PHP. When a method that does not exist in a class is called, the call () method is automatically called, in the form of call ($name, $arguments) where $name is the name of the method, $arguments is an array-type parameter.
The following example uses PHP's method overloads to dynamically create the get and set methods. (in object-oriented programming, a property in a class uses get and set to assign a value, but if there are too many properties in a class, such as 30, then if you do not use the method overload, we need to write 30 set methods, 30 get methods, self side slowly write it ... )
The code is as follows:
<?phpclass person{private $name; private $age; private $address; private $school; private $phonenum; public Function C All ($method, $args) { $perfix =strtolower (substr ($method, 0,3)); $property =strtolower (substr ($method, 3)); if (Empty ($perfix) | | Empty ($property)) { return; } if ($perfix = = "Get" &&isset ($this, $property) { return $this-$property; } if ($perfix = = "Set") { $this, $property = $args [0]; }} $p =new person (); $p->setname (' Lvcy '); $p->setage; $p->setaddress (Chengdu); $p->setschool (' UESTC '); $ P->setphonenum (' 123456 '); Echo $p->getname (). ' \\n '; Echo $p->getage (). ' \\n '; Echo $p->getaddress (). ' \\n '; Echo $p->getschool (). ' \\n ';? >
The call () method solves this problem easily, rather than writing a Get set method for each property.