In PHP, we are not able to implement the method overload directly by means of the same method name, because PHP is a weak data type and is not a good way to distinguish between signatures. However, you can use the __call () method in the PHP class to implement the method overload. When a method that does not exist in a class is invoked, the __call () method is called automatically, in the form of __call ($name, $arguments) where $name is the name of the method, $arguments is an argument of an array type.
The following example uses the method overload of PHP to dynamically create a get and set method. (In object-oriented programming, properties in a class use Get and set to assign values, but if there are too many properties in a class, such as 30, then if you do not use method overload, we need to write 30 set methods, 30 get method, write it slowly from the side ... )
Copy Code code as follows:
<?php
Class Person
{
Private $name;
Private $age;
Private $address;
Private $school;
Private $phonenum;
Public Function __call ($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 (23);
$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 the Get Set method for each property.