今天稍微深入一点点,学习一下几个重要的概念。
一、命名空间
命名空间这个概念是从PHP5.3之后开始引入的,当然PHP7也支持,命名空间主要解决以下两个问题
- 你敲的代码和PHP内部或者是第三方类/函数/常量之间的命名冲突
- 给很长的标识符名称创建一个别名(主要还是为了上一个问题)
命名空间的规则
- 命名空间必须是程序脚本的第一条语句
- 只有类(包括抽象类和traits)、接口、函数和常量受命名空间的影响
1 2 3 4 5 6 7
| <?php namespace MyProject;
const CONNECT_OK = 1; class Connection { } function connect() { } ?>
|
子命名空间
1 2 3 4 5 6 7
| <?php namespace MyProject\Sub\Level;
const CONNECT_OK = 1; class Connection { } function connect() { } ?>
|
命名空间的使用
在文件系统中:
- 相对文件名形式如foo.txt。它会被解析为 currentdirectory/foo.txt,其中 currentdirectory 表示当前目录。因此如果当前目录是 /home/foo,则该文件名被解析为/home/foo/foo.txt。
- 相对路径名形式如subdirectory/foo.txt。它会被解析为 currentdirectory/subdirectory/foo.txt。
- 绝对路径名形式如/main/foo.txt。它会被解析为/main/foo.txt。
那么在命名空间中的元素:
有以下两个文件
1.php
1 2 3 4 5 6 7 8 9 10
| <?php namespace Foo\Bar\subnamespace;
const FOO = 1; function foo() {} class foo { static function staticmethod() {} } ?>
|
2.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| <?php namespace Foo\Bar; include '1.php';
const FOO = 2; function foo() {} class foo { static function staticmethod() {} }
foo(); foo::staticmethod(); echo FOO;
subnamespace\foo(); subnamespace\foo::staticmethod(); echo subnamespace\FOO;
\Foo\Bar\foo(); \Foo\Bar\foo::staticmethod(); echo \Foo\Bar\FOO; ?>
|
常量”NAMESPACE“的值是包含当前命名空间名称的字符串。在全局的,不包括在任何命名空间中的代码,它包含一个空的字符串。
在命名空间中访问全局类
1 2 3 4 5 6 7 8 9
| <?php namespace A\B\C; class Exception extends \Exception {}
$a = new Exception('hi'); $b = new \Exception('hi');
$c = new ArrayObject; ?>
|