Blogger Information
Blog 17
fans 1
comment 0
visits 19905
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
PHP 命名空间与自动加载器原理与实现
大A
Original
707 people have browsed it

命名空间

  • 受命名空间影响的是:类(包括抽象类和traits)、接口、函数和常量
  • 命名空间通过关键字namespace 来声明。如果一个文件中包含命名空间,它必须在其它所有代码之前声明命名空间,除了一个以外:declare关键字。
  • 与目录和文件的关系很象,PHP 命名空间也允许指定层次化的命名空间的名称
  • 可以在同一个文件中定义多个命名空间
  • 命名空间可以通过三种方式引用:非限定名称,限定名称,完全限定名称
  • 别名/导入通过use as 实现
  • 如果没有定义任何命名空间,所有的类与函数的定义都是在全局空间

非限定名称, 限定名称, 完全限定名称,空间的别名与类别名的语法与场景

  1. <?php
  2. //建立一个命名空间a\b\c
  3. namespace a\b\c {
  4. class demo
  5. {
  6. public function print_p($text)
  7. {
  8. return __CLASS__ . '---' . $text . '<br>';
  9. }
  10. }
  11. }
  12. //建立一个命名空间a\b
  13. namespace a\b {
  14. class demo
  15. {
  16. public function print_p($text)
  17. {
  18. return __CLASS__ . '---' . $text . '<br>';
  19. }
  20. }
  21. }
  22. //非限定名称
  23. namespace a\b {
  24. $a = new demo();
  25. echo $a->print_p('非限定名称');
  26. }
  27. //限定名称
  28. namespace a\b {
  29. $a = new c\demo();
  30. echo $a->print_p('限定名称');
  31. }
  32. //完全限定名称
  33. namespace {
  34. //命名空间的类别名
  35. use \a\b\c\demo as demo;
  36. //命名空间的别名
  37. use \a\b\c as c;
  38. $c = new c\demo();
  39. $demo = new demo();
  40. echo $c->print_p('完全限定名称');
  41. echo $demo->print_p('完全限定名称');
  42. }

自动加载

自动加载的条件:

  • 命名空间必须和类文件所在的绝对路径一一对应
  • 当前类名称与当前的类文件的名称完全一致

类文件的自动加载器实现

在根目录下建立一个ns文件夹里面有flie1.php和flie2.php两个文件

flie1.php

  1. <?php
  2. namespace ns;
  3. class file1
  4. {
  5. public $a=456;
  6. public function a()
  7. {
  8. return '我是file1'.'<br>';
  9. }
  10. }

flie2.php

  1. <?php
  2. namespace ns;
  3. class file2
  4. {
  5. public $a=123444;
  6. public function a()
  7. {
  8. return '我是file2'.'<br>';
  9. }
  10. }

autoload.php

  1. <?php
  2. try {
  3. spl_autoload_register("auto");
  4. } catch (Exception $e) {
  5. die($e->getMessage());
  6. }
  7. function auto($classname)
  8. {
  9. $a = __DIR__ . DIRECTORY_SEPARATOR . $classname . '.php';
  10. $a = str_replace('\\', DIRECTORY_SEPARATOR, $a);
  11. require $a;
  12. }

index.php

  1. <?php
  2. require 'autoload.php';
  3. use ns\file1;
  4. use ns\file2;
  5. $f1 = new file1();
  6. echo $f1->a();
  7. $f2 = new file2();
  8. echo $f2->a();
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!