Home  >  Article  >  Backend Development  >  Detailed explanation of get and set method examples of dynamically created properties in PHP

Detailed explanation of get and set method examples of dynamically created properties in PHP

伊谢尔伦
伊谢尔伦Original
2017-07-08 11:04:301657browse

在PHP中,我们不能够直接通过方法名相同,签名不同的方法来实现方法重载,因为PHP是弱数据类型,不能很好的区分签名。但是,可以在PHP的类中运用call()方法来实现方法重载。当调用一个类中并不存在的方法时,会自动调用call()方法,其形式为call($name,$arguments) 其中$name是方法的名称,$arguments是一个数组类型的参数。

下面的例子是使用PHP的方法重载来动态创建get和set方法。(在面向对象编程中,一个类中的属性会使用get和set来赋值,但是如果一个类中有太多的属性,比如30个,那么如果不用方法重载的话,我们就需要写30个set方法,30个get方法,自已一边慢慢写去吧。。。)

代码如下:

<?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(&#39;lvcy&#39;);
$p->setage(23);
$p->setAddress(chengdu);
$p->setschool(&#39;uestc&#39;);
$p->setphonenum(&#39;123456&#39;);
echo $p->getname().&#39;\\n&#39;;
echo $p->getage().&#39;\\n&#39;;
echo $p->getaddress().&#39;\\n&#39;;
echo $p->getschool().&#39;\\n&#39;;
?>

通过Call()方法很容易的解决了这个问题,而不是编写每个属性的get set方法。

The above is the detailed content of Detailed explanation of get and set method examples of dynamically created properties in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn