PHP USES method overloading to implement get and set methods for dynamically creating properties

  • 2020-03-30 04:18:00
  • OfStack

In PHP, we can't override methods directly by signing different methods with the same method name, because PHP is a weak data type and doesn't distinguish signatures well. However, you can use the call() method to implement method reloading in your PHP classes. When calling a method that does not exist in a class, the method is called automatically with the form of arbitration call($name,$arguments) where $name is the name of the method and $arguments is an argument of type array.

The following example USES PHP's method overloading to dynamically create get and set methods. In object-oriented programming, properties in a class are assigned by get and set, but if there are too many properties in a class, like 30, then we need to write 30 set methods and 30 get methods without method overloading.


<?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';
?>

Instead of writing a get set method for each property, you can easily solve this problem by using the successive call () method.


Related articles: