Blogger Information
Blog 46
fans 0
comment 0
visits 34322
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
PHP实例演示属性与方法重载
上草一方
Original
670 people have browsed it

代码如下:

  1. <?php
  2. /**
  3. * 1.属性重载:__get(),set__()
  4. * 2.方法属性:__call(),__callStatic()
  5. */
  6. class User
  7. {
  8. // 属性
  9. private $data = ['age'=>20];
  10. //查询拦截器
  11. public function __get($name){
  12. //$name:属性名
  13. // return $this->name;
  14. if (array_key_exists($name,$this->data)) {
  15. return $this->data[$name];
  16. }
  17. return "属性{$name}不存在";
  18. }
  19. //更新拦截器
  20. public function __set($name,$value)
  21. {
  22. //1.有没有这个属性?
  23. if (array_key_exists($name,$this->data)){
  24. //2.这个值是否合法?
  25. if ($name === 'age') {
  26. if ($value>=18 && $value<=59) {
  27. $this->data[$name] = $value;
  28. } else {
  29. echo '年龄必须在18-59岁之间';
  30. }
  31. } else {
  32. // 以上操作仅对age有效,其它属性值直接赋值
  33. $this->data[$name] = $value;
  34. }
  35. } else {
  36. echo '禁止动态创建属性';
  37. }
  38. }
  39. //方法拦截器
  40. public function __call($name,$args){
  41. // $name:方法名,$args:传给方法的参数
  42. printf('方法:%s<br>参数:<pre>%s</pre>',$name,print_r($args,true));
  43. }
  44. //静态方法拦截器
  45. public static function __callStatic($name,$args){
  46. // $name:方法名, $args:传给方法的参数
  47. printf('方法:%s<br>参数:<pre>%s</pre>',$name,print_r($args,true));
  48. }
  49. }
  50. $user = new User;
  51. echo $user->name.'<br>';
  52. /**
  53. * 为一个属性赋值的时候,必须要搞清楚2件事
  54. * 1. 有没有这个属性?
  55. * 2. 这个值是否合法?
  56. */
  57. $user->age = 29;
  58. echo $user->age.'<br>';
  59. echo '<hr>';
  60. // 常规方法/非静态方法/用实例调用
  61. $user->hello('猪老师', 'php.cn');
  62. echo '<hr>';
  63. // 静态方法
  64. User::world(100,200);

运行后效果如下:

Correcting teacher:PHPzPHPz

Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post