Blogger Information
Blog 26
fans 0
comment 0
visits 18135
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
命名空间与类文件的自动加载
雪~人胖胖
Original
853 people have browsed it

1.命名空间

  1. namespace user1
  2. {
  3. class Demo1
  4. {
  5. const NAME = '这是user1下的Demo1';
  6. }
  7. }
  8. namespace user2
  9. {
  10. class Demo1{
  11. const NAME ='这是user2下的Demo1';
  12. }
  13. //访问另一个空间的成员,必须使用完全限定名称,根目录用'\'表示
  14. //访问user1下的类
  15. echo \user1\Demo1::NAME.'<br>';
  16. //非限定名称:在访问空间成员前面没有命名空间
  17. echo Demo1::NAME.'<br>';
  18. //限定名称:不是从根目录找起,访问成员前至少有一个命名空间,从当前位置找起
  19. echo user3\Demo1::NAME;
  20. //当前空间没有该函数,会到全局空间去找
  21. echo write();
  22. }
  23. namespace user2\user3
  24. {
  25. class Demo1
  26. {
  27. const NAME ='这是user3下的Demo1';
  28. }
  29. }
  30. //创建一个全局的空间,匿名空间
  31. namespace
  32. {
  33. function write()
  34. {
  35. return '我是在全局空间的函数';
  36. }
  37. }

2.命名空间的别名, 与类别名

  1. namespace ns1
  2. {
  3. class A1
  4. {
  5. public static function write()
  6. {
  7. return 'A1的方法';
  8. }
  9. }
  10. }
  11. namespace ns2
  12. {
  13. class A2
  14. {
  15. public static function write()
  16. {
  17. return 'A2的方法';
  18. }
  19. }
  20. }
  21. namespace
  22. { //给ns1空间起别名
  23. use ns1 as T;
  24. //给ns2空间的A2类起别名
  25. //use ns2\A2 as A2;
  26. //当类名和别名一样是可以简写
  27. use ns2\A2;
  28. echo T\A1::write().'<br>';
  29. echo A2::write().'<br>';
  30. }

类文件的自动加载

__DIR__:文件所在的目录
DIRECTORY_SEPARATOR:系统分隔符

  1. //注册自动加载器
  2. spl_autoload_register(function($className)
  3. { //将类名中的命名空间的分隔符转化为目录分隔符
  4. $path = str_replace('\\',DIRECTORY_SEPARATOR,$className);
  5. //生成文件名称
  6. $file=__DIR__.DIRECTORY_SEPARATOR.$className.'.php';
  7. //加载文件
  8. require $file;
  9. });
  10. //要加载的文件的处理
  11. //要实现自动加载要满足的条件
  12. //1.命名空间必须与类文件所在的绝对路径一致
  13. //2.当前类名与当前类文件名一致
  14. //namespace inc\lib
  15. //{
  16. // class Demo1
  17. // {
  18. // public static function write()
  19. // {
  20. // return '这是1';
  21. // }
  22. // }
  23. //}
  24. use inc\lib\Demo1;
  25. use inc\lib\Demo2;
  26. echo Demo1::write().'<br>';
  27. echo Demo2::write();

总结

基本了解了命名空间的三种访问形式完全限定名称,限定名称和非限定名称,命名空间可以避免组件加载时的命名冲突,自动加载很好的解决了需要加载多个文件就要写多个require的问题。

Correcting teacher:天蓬老师天蓬老师

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!