命名空间是在php5.3版本以加入的。
命名空间一个最明确的目的就是解决重名问题,PHP中不允许两个函数或者类出现相同的名字,否则会产生一个致命的错误。
默认情况下,所有常量、类和函数名都放在全局空间下,就和PHP支持命名空间之前一样。
命名空间通过关键字namespace 来声明。如果一个文件中包含命名空间,它必须在其它所有代码之前声明命名空间。
比如,我们创建一个文件:student.php
<?php
namespace model; //定义命名间
//类Student在model命名空间中
class Student
{
public function say(){
echo 'hello';
}
}
我们创建一个测试文件:test.php
<?php
use model\Student; //引入 model命名空间的Student 类
require_once 'student.php';
$stu = new Student();
$stu->say();
要想使用命名空间中的类,必须要引入这个类,如:use model\Student
引入命名空间的类时,也可以给类重新命名,原有的类名不能再使用。
<?php
use model\Student as Stu; //引入 model命名空间的Student 类,并重命名为Stu
require_once 'student.php';
$stu = new Stu();
$stu->say();
在有些场景下必须给类重新命名,比如还有一个类也是Student,在文件student2.php中
<?php
namespace controller;
class Student
{
public function showme()
{
echo '自我介绍';
}
}
那么在test.php中如何同时使用这两个student类呢?
<?php
use model\Student as StuModel;
use controller\Student as StuController;
require_once 'student.php';
require_once 'student2.php';
$stu1 = new StuModel();
$stu1->say();
$stu2= new StuController();
$stu2->showme();
给引入的类重新命名,解决了难题。
在后续的课程中,我们定义的类都使用了命名空间。