当前位置:Gxlcms > PHP教程 > php实现动态创建属性的get和set方法实例详解

php实现动态创建属性的get和set方法实例详解

时间:2021-07-01 10:21:17 帮助过:34人阅读

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

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

代码如下:

  1. <?php
  2. class person
  3. {
  4. private $name;
  5. private $age;
  6. private $address;
  7. private $school;
  8. private $phonenum;
  9. public function call($method,$args)
  10. {
  11. $perfix=strtolower(substr($method,0,3));
  12. $property=strtolower(substr($method,3));
  13. if(empty($perfix)||empty($property))
  14. {
  15. return;
  16. }
  17. if($perfix=="get"&&isset($this->$property))
  18. {
  19. return $this->$property;
  20. }
  21. if($perfix=="set")
  22. {
  23. $this->$property=$args[0];
  24. }
  25. }
  26. }
  27. $p=new person();
  28. $p->setname('lvcy');
  29. $p->setage(23);
  30. $p->setAddress(chengdu);
  31. $p->setschool('uestc');
  32. $p->setphonenum('123456');
  33. echo $p->getname().'\\n';
  34. echo $p->getage().'\\n';
  35. echo $p->getaddress().'\\n';
  36. echo $p->getschool().'\\n';
  37. ?>

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

以上就是php实现动态创建属性的get和set方法实例详解的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行