Blogger Information
Blog 38
fans 0
comment 0
visits 18945
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
实例演示属性与方法重载、 实例演示命名空间与类自动加载器
Blackeye
Original
389 people have browsed it

1

  1. <?php
  2. // 1. 实例演示属性与方法重载
  3. // 1. 属性重载:__get(), __set()
  4. class hw{
  5. private $data=[
  6. 'age'=>20
  7. ];
  8. // 查询拦截器
  9. public function __get($name){
  10. return $this->data[$name];
  11. }
  12. // 更新拦截器
  13. public function __set($name,$value){
  14. if($value<99){
  15. return $this->data[$name] = $value;
  16. }else{
  17. echo "请输入合法年龄" . "<hr>";
  18. }
  19. }
  20. // 2. 方法重载:__call(),__callStatic()
  21. public function __call($name, $args){
  22. printf("方法:%s,<br/>参数:<pre>%s</pre>",$name,print_r($args,true));
  23. }
  24. public static function __callStatic($name, $args){
  25. printf("方法:%s,<br/>参数:<pre>%s</pre>",$name,print_r($args,true));
  26. }
  27. }
  28. $HW = new hw;
  29. echo $HW->age . "<hr>";
  30. $HW->age = 101;
  31. $HW->age = 98;
  32. echo $HW->age . "<hr>";
  33. $HW->add(1,2,3,4,5,6,7,8,9);
  34. hw::name("Dave","Sarah");

2

  1. <?php
  2. // 2. 实例演示命名空间与类自动加载器
  3. namespace ns1{
  4. const ns = ".cn";
  5. }
  6. namespace {
  7. const ns = "php";
  8. echo ns . "<hr>";
  9. echo ns1\ns . "<hr>";
  10. echo \ns1\ns . "<hr>";
  11. }

3

  1. <?php
  2. // 类自动加载器
  3. spl_autoload_register(function($class){
  4. $path = str_replace('\\', DIRECTORY_SEPARATOR, $class);
  5. $file = __DIR__ . DIRECTORY_SEPARATOR . $path . '.php';
  6. require $file;
  7. });
  8. new \com\HW;

路径com下的HW.php

  1. <?php
  2. namespace com;
  3. class HW{
  4. }
  5. echo HW::class . "<br/>";
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