PHP命名空间是PHP5.3开始支持。本篇讲解PHP命名空间用法和PHP命名空间详解。它的诞生使的我们在一个文件中可以使用多个同名的类而不冲突。
好处:我们的项目有一个记录日志文件的类,叫做Log。然后我们又必须要引入另一个代码包,这个代码包里也有一个叫做Log的类。那么在一个文件中,我们记录日志的又需要给两个类都写一条日志。可以类同名了,怎么办?这个时候,命名空间应运而生。在Java等语言中命名空间是很早就已经提供了支持,而我大PHP一直到5.3才对命名空间提供了支持。
示例一:
文件index.php
include 'test.php';
class index{
public function a(){
echo basename(__FILE__);
echo '
';
echo __CLASS__ . ' : ' . __METHOD__;
}
}
$obj = new index();
$obj->a();
echo '
';
$obj1 = new test\index();
$obj1->a();
?>
文件test.php
namespace test;
class index{
public function a(){
echo basename(__FILE__);
echo '
';
echo __CLASS__ . ' : ' . __METHOD__;
}
}
?>
我们给index.php不设置命名空间,对test.php设置命名空间,名为test。运行index.php。
结果:
index.php
index : index::a
test.php
test\index : test\index::a
我们看到了,同名的类也可以运行而不冲突了。
示例二:
文件index.php
namespace index;
include 'test.php';
class index{
public function a(){
echo basename(__FILE__);
echo '
';
echo __CLASS__ . ' : ' . __METHOD__;
}
}
$obj = new index();
$obj->a();
echo '
';
$obj1 = new \test\index();
$obj1->a();
?>
文件test.php
namespace test;
class index{
public function a(){
echo basename(__FILE__);
echo '
';
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
namespace index;
include 'namespace.php';
use \test\test1\test2 as test2;
class index{
public function a(){
echo basename(__FILE__);
echo '
';
echo __CLASS__ . ' : ' . __METHOD__;
}
}
$obj = new index();
$obj->a();
echo '
';
$obj1 = new \test\test1\test2\index();
$obj1->a();
echo '
';
$obj1 = new test2\index();
$obj1->a();
文件test.php
namespace test\test1\test2;
class index{
public function a(){
echo basename(__FILE__);
echo '
';
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关键字。示例如下(摘自官方手册示例):
use My\Full\Classname as Another, My\Full\NSname;
$obj = new Another; // 实例化一个 My\Full\Classname 对象
$a = 'Another';
$obj = new $a; // 实际化一个 Another 对象
荒野乱斗国际版 (BrawlStars)最新版本v56.274
下载一波超人内置修改器菜单版 安卓版v1.0.2
下载敢达决战官方正版 安卓版v6.7.9
下载敢达决战 安卓版v6.7.9
下载继承了一座戏园子无限声望铜钱版 内置菜单最新版v1.7
继承了一座戏园子折相思版是游戏的破解版本,在该版本中为玩家提
山河半世橙光清软金手指版 无限鲜花v3.24
山河半世是一款超级好玩的橙光恋爱游戏,在游戏中玩家们需要扮演
蓬莱手游折相思版 安卓版v1.0.0
蓬莱免广告版是游戏的修改版本,在该版本中为玩家去除了广告,玩
当红影后橙光游戏破解版2025 最新版v1.0
当红影后橙光破解版是一款超级好玩的娱乐圈题材的橙光游戏,在这
忽然成了万人迷清软完结版 无限鲜花版v12.15
忽然成了万人迷破解版是一款非常好玩的男性向橙光游戏,在有一天