Blogger Information
Blog 94
fans 0
comment 0
visits 92492
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
【PHP】命名空间和自动加载
可乐随笔
Original
1570 people have browsed it

命名空间和自动加载

1.命名空间

  1. <?php
  2. //空间别名
  3. namespace ns1;
  4. // echo \ns1\ns2\Demo1::hello() .PHP_EOL;
  5. // echo ns2\Demo1::hello() .PHP_EOL;
  6. // echo ns2\ns3\Demo1::world() .PHP_EOL;
  7. //简化命名空间名称: use
  8. use \ns1\ns2\Demo1 as D1;
  9. use \ns1\ns2\ns3\Demo1 as D2;
  10. echo D1::hello() .PHP_EOL;
  11. echo D2::world() .PHP_EOL;
  12. namespace ns1\ns2;
  13. class Demo1{
  14. public static function hello()
  15. {
  16. return __METHOD__ .'()';
  17. }
  18. }
  19. namespace ns1\ns2\ns3;
  20. class Demo1{
  21. public static function world()
  22. {
  23. return __METHOD__ .'()';
  24. }
  25. }

2.类的自动加载

  1. <?php
  2. // 类的自动加载
  3. // 原理:将命名空间,映射到类文件的路径上
  4. // 1.类名 <->类文件名
  5. // 2.类空间 <-> 类文件的路径
  6. namespace zhu;
  7. // 传统
  8. // require __DIR__ . '/admin/controller/Index.php';
  9. // require __DIR__ . '/admin/model/User.php';
  10. // require __DIR__ . '/admin/view/index/Hello.php';
  11. // 注册类的自动加载器
  12. spl_autoload_register(function ($class) {
  13. // echo $class . PHP_EOL;
  14. // 类名:admin\controller\Index
  15. // 类文件名: admin\controller\Index.php
  16. // 将路径分隔符替换"
  17. $path = str_replace('\\', DIRECTORY_SEPARATOR, $class);
  18. // echo $path .PHP_EOL;
  19. $file = __DIR__. '/' . $path. '.php';
  20. if (is_file($file) && file_exists($file))
  21. {
  22. require $file;
  23. } else {
  24. die($file . '不存在');
  25. }
  26. });
  27. use admin\controller\Index;
  28. use admin\model\User;
  29. use admin\view\index\Hello;
  30. echo Index::show() .PHP_EOL;
  31. echo User::show() .PHP_EOL;
  32. echo Hello::show() .PHP_EOL;
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