PHP命名空间 __NAMESPACE__

猫斯基 28 2014-01-30

任意合法的PHP代码都可以包含在命名空间中,但只有三种类型的代码受命名空间影响:类、函数、常量。

命名空间声明的关键字是 namespace

namespace声明命名空间的代码之前不能有任何PHP代码和HTML内容输出,除了declare()

定义多个命名空间,以最后一个为主,前面的就覆盖掉了。

__NAMESPACE__表示当前的命名空间。

namespace mao;
const A = 1;
class Demo{
	static function one() {
		echo '111
'; } } function test(){ echo 'test
'; } maotest(); maoDemo::one(); echo maoA; /* 打印结果: test 111 1 */

子命名空间

namespace maomaosiji;
const A = 1;
class Demo{
	static function one() {
		echo '111
'; } } function test(){ echo 'test
'; } maomaosijitest(); maomaosijiDemo::one(); echo maomaosijiA; /* 打印结果: test 111 1 */

多个命名空间

不建议用多个命名空间。

如果用的话,不要在命名空间后面的大括号外面加任何PHP代码。

namespace maomaosiji{
	const A = 1;
	class Demo{
		static function one() {
			echo '111
'; } } function test(){ echo 'test
'; } maomaosijitest(); maomaosijiDemo::one(); echo maomaosijiA; }; namespace maocom{ const B = 2; echo maocomB; };

__NAMESPACE__

namespace maomaosiji{
	const A = 1;
	class Demo{
		static function one() {
			echo '111
'; } } function test(){ echo 'test
'; } __NAMESPACE__.test(); __NAMESPACE__.Demo::one(); echo __NAMESPACE__.A; }; /* 打印结果: test 111 1 */

命名空间别名

namespace maomaosijicomhello;
use maomaosijicomhello as m;
	const A = 1;
	class Demo{
		static function one() {
			echo '111
'; } } function test(){ echo 'test
'; } m.test(); m.Demo::one(); echo m.A; /* 打印结果: test 111 1 */
namespace maomaosijicomhello;
use maomaosijicomhello;
	const A = 1;
	class Demo{
		static function one() {
			echo '111
'; } } function test(){ echo 'test
'; } hello.test(); hello.Demo::one(); echo hello.A; /* 打印结果: test 111 1 */

本文由 猫斯基 原创发布。

著作权均归用户本人所有。独家文章转载,请联系本站管理员。获得授权后,须注明本文地址! 本文地址:https://www.maosiji.com/2575.html