[关闭]
@Chiang 2020-01-10T10:58:12.000000Z 字数 1942 阅读 540

命名空间和动态语言特征

PHP


PHP 命名空间的实现受到其语言自身的动态特征的影响。因此,如果要将下面的代码转换到命名空间中:

  1. <?php
  2. class classname
  3. {
  4. function __construct()
  5. {
  6. echo __METHOD__,"\n";
  7. }
  8. }
  9. function funcname()
  10. {
  11. echo __FUNCTION__,"\n";
  12. }
  13. const constname = "global";
  14. $a = 'classname';
  15. $obj = new $a; // prints classname::__construct
  16. $b = 'funcname';
  17. $b(); // prints funcname
  18. echo constant('constname'), "\n"; // prints global
  19. ?>

必须使用完全限定名称(包括命名空间前缀的类名称)。注意因为在动态的类名称、函数名称或常量名称中,限定名称和完全限定名称没有区别,因此其前导的反斜杠是不必要的。

  1. <?php
  2. namespace namespacename;
  3. class classname
  4. {
  5. function __construct()
  6. {
  7. echo __METHOD__,"\n";
  8. }
  9. }
  10. function funcname()
  11. {
  12. echo __FUNCTION__,"\n";
  13. }
  14. const constname = "namespaced";
  15. include 'example1.php';
  16. $a = 'classname';
  17. $obj = new $a; // prints classname::__construct
  18. $b = 'funcname';
  19. $b(); // prints funcname
  20. echo constant('constname'), "\n"; // prints global
  21. /* note that if using double quotes, "\\namespacename\\classname" must be used */
  22. $a = '\namespacename\classname';
  23. $obj = new $a; // prints namespacename\classname::__construct
  24. $a = 'namespacename\classname';
  25. $obj = new $a; // also prints namespacename\classname::__construct
  26. $b = 'namespacename\funcname';
  27. $b(); // prints namespacename\funcname
  28. $b = '\namespacename\funcname';
  29. $b(); // also prints namespacename\funcname
  30. echo constant('\namespacename\constname'), "\n"; // prints namespaced
  31. echo constant('namespacename\constname'), "\n"; // also prints namespaced
  32. ?>

请一定别忘了阅读 对字符串中的命名空间名称转义的注解.

Dynamic namespace names (quoted identifiers) should escape backslash

  • It is very important to realize that because the backslash is used as an escape character within strings, it should always be doubled when used inside a string. Otherwise there is a risk of unintended consequences:
  • Example #9 Dangers of using namespaced names inside a double-quoted string
  1. <?php
  2. $a = new "dangerous\name"; // \n is a newline inside double quoted strings!
  3. $obj = new $a;
  4. $a = new 'not\at\all\dangerous'; // no problems here.
  5. $obj = new $a;
  6. ?>

Inside a single-quoted string, the backslash escape sequence is much safer to use, but it is still recommended practice to escape backslashes in all strings as a best practice.

我的理解:

  • ""''的区别
  • \最后写成\\转义字符
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注