In PHP, we cannot directly implement method overloading by methods with the same method name and different signatures, because PHP is a weak data type and cannot distinguish signatures well. However, you can use the __call() method in PHP classes to implement method overloading. When a method that does not exist in a class is called, the __call() method is automatically called, which is in the form of __call($name,$arguments) where $name is the name of the method and $arguments is an array type parameter.
The following example is to use PHP method overload to dynamically create get and set methods. (In object-oriented programming, the properties in a class will be assigned using get and set, but if there are too many properties in a class, such as 30, then if we do not use method overload, we need to write 30 set methods and 30 get methods, and write them slowly on our own...)
The code copy is 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';
?>
This problem is easily solved by __Call() method, rather than writing a get set method for each property.