PHP命名空间 __NAMESPACE__
任意合法的PHP代码都可以包含在命名空间中,但只有三种类型的代码受命名空间影响:类、函数、常量。
命名空间声明的关键字是 namespace
。
在namespace
声明命名空间的代码之前不能有任何PHP代码和HTML内容输出,除了declare()
。
定义多个命名空间,以最后一个为主,前面的就覆盖掉了。
__NAMESPACE__
表示当前的命名空间。
/* 猫斯基 maosiji.com */ namespace mao; const A = 1; class Demo{ static function one() { echo '111<br>'; } } function test(){ echo 'test<br>'; } \mao\test(); \mao\Demo::one(); echo \mao\A; /* 打印结果: test 111 1 */
子命名空间
/* 猫斯基 maosiji.com */ namespace mao\maosiji; const A = 1; class Demo{ static function one() { echo '111<br>'; } } function test(){ echo 'test<br>'; } \mao\maosiji\test(); \mao\maosiji\Demo::one(); echo \mao\maosiji\A; /* 打印结果: test 111 1 */
多个命名空间
不建议用多个命名空间。
如果用的话,不要在命名空间后面的大括号外面加任何PHP代码。
/* 猫斯基 maosiji.com */ namespace mao\maosiji{ const A = 1; class Demo{ static function one() { echo '111<br>'; } } function test(){ echo 'test<br>'; } \mao\maosiji\test(); \mao\maosiji\Demo::one(); echo \mao\maosiji\A; }; namespace mao\com{ const B = 2; echo \mao\com\B; };
__NAMESPACE__
/* 猫斯基 maosiji.com */ namespace mao\maosiji{ const A = 1; class Demo{ static function one() { echo '111<br>'; } } function test(){ echo 'test<br>'; } __NAMESPACE__.test(); __NAMESPACE__.Demo::one(); echo __NAMESPACE__.A; }; /* 打印结果: test 111 1 */
命名空间别名
/* 猫斯基 maosiji.com */ namespace mao\maosiji\com\hello; use mao\maosiji\com\hello as m; const A = 1; class Demo{ static function one() { echo '111<br>'; } } function test(){ echo 'test<br>'; } m.test(); m.Demo::one(); echo m.A; /* 打印结果: test 111 1 */
/* 猫斯基 maosiji.com */ namespace mao\maosiji\com\hello; use mao\maosiji\com\hello; const A = 1; class Demo{ static function one() { echo '111<br>'; } } function test(){ echo 'test<br>'; } hello.test(); hello.Demo::one(); echo hello.A; /* 打印结果: test 111 1 */