博主信息
博文 32
粉丝 2
评论 0
访问量 37775
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
三种类名称及自动加载器实现类的自动加载
简行
原创
745人浏览过

一.三种类名称:完全限定,限定与非限定

代码:

  1. <?php
  2. //命名空间:ns1
  3. namespace ns1;
  4. class demo
  5. {
  6. public function index(){
  7. return "这是命名空间ns1中的类demo中的方法index";
  8. }
  9. }
  10. //命名空间:ns3\ns2
  11. namespace ns3\ns2;
  12. class demo
  13. {
  14. public static function index(){
  15. return "这是命名空间ns3\\ns2中的类demo中的方法index";
  16. }
  17. }
  18. //命名空间:ns3
  19. namespace ns3;
  20. class demo
  21. {
  22. public static function index(){
  23. return "这是命名空间ns3中的类demo中的方法index";
  24. }
  25. }
  26. // \ns1\demo:完全限定名称类名,以"\"开头,类似绝对路径
  27. echo "完全限定名称访问:".(new \ns1\demo)->index();
  28. echo "<hr>";
  29. // ns2\demo:限定名称类名,不以"\"开头,并带有空间名称,类似行动对路径
  30. echo "限定名称访问:".(new ns2\demo)->index();
  31. echo "<hr>";
  32. //直接访问本空间成员
  33. echo "非限定名称访问:".(new demo)->index();
  34. echo "<hr>";

二.自动加载器实现类的自动加载

代码部分:

  1. <?php
  2. try {
  3. spl_autoload_register(function($class){
  4. // DIRECTORY_SEPARATOR:可随操作系统不同,使用不同的目录分隔符
  5. $path = str_replace("\\",DIRECTORY_SEPARATOR,$class);
  6. $file = __DIR__.DIRECTORY_SEPARATOR.$path.".php";
  7. //is_file():判断是否是文件,返回布尔值
  8. //file_exists():判断文件是否是存在,返回布尔值
  9. if(!(is_file($file) && file_exists($file))){
  10. exit("文件不存在:".$file);
  11. }
  12. require $file;
  13. });
  14. } catch (Exception $e) {
  15. exit($e ->getMessage());
  16. }
  17. // use admin\user\auth\Index1 as index1;
  18. echo "类的自动加载:".index1::class."<br>";
  19. echo "类的自动加载的方法:".(new \admin\user\auth\Index1)->test();

编辑器文件截图:

前端截图:

总结:
1.不清楚加载器怎么实现函数的自动加载;
2.不太理解spl_autoload_register(function($class){}$class这个参数

批改老师:天蓬老师天蓬老师

批改状态:合格

老师批语:这个参数就是类名称, 这是回调参数的规定, 没什么要理解,记住就可以
本博文版权归博主所有,转载请注明地址!如有侵权、违法,请联系admin@php.cn举报处理!
全部评论 文明上网理性发言,请遵守新闻评论服务协议
0条评论
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号

  • 登录PHP中文网,和优秀的人一起学习!
    全站2000+教程免费学