Blogger Information
Blog 29
fans 0
comment 0
visits 14061
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
属性方法重载学习小结
P粉317509817
Original
426 people have browsed it

属性方法重载

  1. <?php
  2. // 属性重载:__get(),__set()
  3. // 方法重载:__call(),__callStatic()
  4. class Person1
  5. {
  6. private $data = [
  7. 'name'=>'xyz',
  8. 'age'=>20
  9. ];
  10. // 查询拦截器
  11. public function __get($name)
  12. {
  13. if (array_key_exists($name,$this->data)){
  14. return $this->data[$name];
  15. }
  16. return "属性{$name}不存在";
  17. }
  18. // 跟新拦截器
  19. public function __set($name,$value){
  20. // 查询有无属性
  21. if(array_key_exists($name,$this->data)){
  22. // 如果有属性,则支持属性修改
  23. // 对姓名进行改写
  24. if ($name==='name'){
  25. $this->data[$name]=$value;
  26. }
  27. elseif($name === 'age'){
  28. $this->data[$name]=$value;
  29. }
  30. }
  31. else{
  32. echo "禁止动态创建属性";
  33. }
  34. }
  35. // 方法拦截器
  36. public function __call($name,$args){
  37. // $name: 方法名, $args: 传给方法的参数
  38. printf('方法: %s<br>参数:<pre>%s</pre>', $name, print_r($args, true));
  39. }
  40. // 静态方法拦截器
  41. public static function __callStatic($name, $arguments)
  42. {
  43. printf('方法: %s<br>参数:<pre>%s</pre>', $name, print_r($arguments, true));
  44. }
  45. }
  46. $person = new Person1;
  47. echo $person->name.'<br>';
  48. echo '<hr color=red>';
  49. // 常规方法/非静态方法/用实例调用
  50. $person->hello('dfas', '20');
  51. // 静态方法
  52. Person1::world(100, 200);

效果:

命名空间

创建四个demo.php在/php/cn目录中

  1. <?php
  2. namespace php\cn;
  3. class demo1
  4. {
  5. }
  6. echo demo1::class.'<br>';

注册机写法

  1. <?php
  2. spl_autoload_register(function($class){
  3. $path= str_replace('\\',DIRECTORY_SEPARATOR,$class);
  4. $file = __DIR__.DIRECTORY_SEPARATOR.$path.'.php';
  5. require $file;
  6. });

最后调用

  1. <?php
  2. namespace ns1;
  3. require __DIR__.'/autoloader.php';
  4. class demo2{
  5. }
  6. echo demo2::class.'<br>';
  7. echo \php\cn\demo2::class;

写法

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