PHP命名空间是PHP5.3开始支持。本篇讲解PHP命名空间用法和PHP命名空间详解。它的诞生使的我们在一个文件中可以使用多个同名的类而不冲突。
好处:我们的项目有一个记录日志文件的类,叫做Log。然后我们又必须要引入另一个代码包,这个代码包里也有一个叫做Log的类。那么在一个文件中,我们记录日志的又需要给两个类都写一条日志。可以类同名了,怎么办?这个时候,命名空间应运而生。在Java等语言中命名空间是很早就已经提供了支持,而我大PHP一直到5.3才对命名空间提供了支持。
示例一:
文件index.php
<?php
include \'test.php\';
class index{
public function a(){
echo name(__FILE__);
echo \'<br>\';
echo __CLASS__ . \' : \' . __METHOD__;
}
}
$obj = new index();
$obj->a();
echo \'<br>\';
$obj1 = new test\index();
$obj1->a();
?>
文件test.php
<?php
namespace test;
class index{
public function a(){
echo name(__FILE__);
echo \'<br>\';
echo __CLASS__ . \' : \' . __METHOD__;
}
}
?>
我们给index.php不设置命名空间,对test.php设置命名空间,名为test。运行index.php。
结果:
index.php
index : index::a
test.php
test\index : test\index::a
我们看到了,同名的类也可以运行而不冲突了。
示例二:
文件index.php
<?php
namespace index;
include \'test.php\';
class index{
public function a(){
echo name(__FILE__);
echo \'<br>\';
echo __CLASS__ . \' : \' . __METHOD__;
}
}
$obj = new index();
$obj->a();
echo \'<br>\';
$obj1 = new \test\index();
$obj1->a();
?>
文件test.php
<?php
namespace test;
class index{
public function a(){
echo name(__FILE__);
echo \'<br>\';
echo __CLASS__ . \' : \' . __METHOD__;
}
}
?>
我们给index.php设置命名空间,名为index,对test.php设置命名空间,名为test。运行index.php。
结果:
index.php
index\index : index\index::a
test.php
test\index : test\index::a
比较示例一和二,不对index.php设置命名空间,即该文件是整个PHP全局命名空间下面的一个文件,那么使用test\index()即可,如果对index.php设置命名空间,即在其他的命名空间中使用命名空间,就要多一个“\”,就要使用\test\index()。
示例三:
文件index.php
<?php
namespace index;
include \'namespace.php\';
use \test\test1\test2 as test2;
class index{
public function a(){
echo name(__FILE__);
echo \'<br>\';
echo __CLASS__ . \' : \' . __METHOD__;
}
}
$obj = new index();
$obj->a();
echo \'<br>\';
$obj1 = new \test\test1\test2\index();
$obj1->a();
echo \'<br>\';
$obj1 = new test2\index();
$obj1->a();
文件test.php
<?php
namespace test\test1\test2;
class index{
public function a(){
echo name(__FILE__);
echo \'<br>\';
echo __CLASS__ . \' : \' . __METHOD__;
}
}
结果:
index.php
index\index : index\index::a
test.php
test\test1\test2\index : test\test1\test2\index::a
test.php
test\test1\test2\index : test\test1\test2\index::a
这说明了什么?别名!用过SQL吧。
select COUNT(*) as `count` from `tebleName`
嗯,一个意思。\test\test1\test2这个名字太长了,就别名为test2就好了。使用了use之后呢,这个命名空间就想到于是在index这个命名空间下面了,而不是全局命名空间的一员了,所以使用test2\index(),而不是\test2\index()。
别名时在PHP代码编译的时候执行的,而变量的解析则要更晚。也就是说不能对变量运用use关键字。示例如下(摘自官方手册示例):
<?php
use My\Full\Classname as Another, My\Full\NSname;
$obj = new Another; // 实例化一个 My\Full\Classname 对象
$a = \'Another\';
$obj = new $a; // 实际化一个 Another 对象
?>
继续阅读与本文标签相同的文章
-
中国第4大运营商来袭,携号转网套路多,移不动联不通信不过拜拜
2026-05-14栏目: 教程
-
美国让华为更强大,9个月入账6千亿增速超2成,5G合同已签60多份
2026-05-14栏目: 教程
-
未来几年,这4个大学专业最吃香,前景广阔堪称铁饭碗!
2026-05-14栏目: 教程
-
这间屋子没有电话
2026-05-14栏目: 教程
-
曾经扬言“我要摧毁人类”的机器人,在拥有公民身份后,近况如何?
2026-05-14栏目: 教程
