一、概述
名称:命名空间
关键字:namespace
目的:解决数据名称冲突,提高代码可读性
格式:namespace 空间名
举例:
<?php
namespace Test;
二、代码实现
1.目录搭建
|-Works
|---Common
|-----Test_1.class.php
|---Lib
|-----Test.class.php
|---index.php
2.Common/Test_1.class.php
<?php
namespace Common;
class Test {
public function g(){
echo __FILE__;
}
}
3.Lib/Test.class.php
<?php
namespace Lib;
class Test {
public function g(){
echo __FILE__;
}
}
3.index.php
<?php
//引入文件
include_once "Lib/Test.class.php";
include_once "Common/Test_1.class.php";
//实例化
$t1=new Lib\Test;//使用命名空间实例化类
$t1->g();
echo "<br/>";
//实例化
$t2=new Common\Test;
$t2->g();
4.运行结果
E:\wamp\www\Work\Lib\Test.class.php
E:\wamp\www\Work\Common\Test_1.class.php
备注:当我们运行后会发现,在index.php文件中同时引入两个同类名Test的类文件,却不会报错,其原因就是命名空间解决了同名的冲突,但是在实例化类的时候注意要带上命名空间,不然会出错!