PHP命名空间背景与基本概念
本实例详细解析了PHP中命名空间(namespace)的声明机制以及通过use进行导入的具体操作方式,旨在为开发者提供实用的参考指南。
在PHP语言规范中,全局范围内不允许存在名称相同的函数或类。为了规避开发人员在实际项目中因类名或函数名重复而引发的冲突隐患,PHP 5.3版本正式引入了命名空间特性。
1. 命名空间的核心作用是将代码划分为不同的逻辑区域,确保各个区域内的类名相互独立,避免相互覆盖。一个PHP文件中允许包含多个命名空间定义,但首个命名空间之前严禁放置任何非空白字符。一旦声明了命名空间,其后的代码即归属于该空间,具体示例如下:
<?php
echo 111; //由于namespace前有代码而报错
namespace Teacher;
class Person{
function __construct(){
echo 'Please study!';
}
}
2. 访问位于不同命名空间中的类或方法时,必须显式指明其所属的命名空间路径。例如:
<?php
namespace Teacher;
class Person{
function __construct(){
echo 'Please study!
';
}
}
function Person(){
return 'You must stay here!';
};
namespace Student;
class Person{
function __construct(){
echo 'I want to play!
';
}
}
new Person(); //本空间(Student空间)
new \Teacher\Person(); //Teacher空间
new \Student\Person(); //Student空间
echo \Teacher\Person(); //Teacher空间下Person函数
执行结果输出:
I want to play!
Please study!
I want to play!
You must stay here!
3. 在某个命名空间内部通过include或require引入外部文件时,被引入文件的代码并不会自动归入当前命名空间,而是处于全局公共空间或遵循文件自身定义的命名结构。演示案例如下:
首先创建两个独立的PHP文件:1.php 和 2.php:
<?php //1.php
class Person{
function __construct(){
echo 'I am one!
';
}
}
<?php
namespace Newer;
require_once './1.php';
new Person(); //报错,找不到Person;
new \Person(); //输出 I am tow!;
<?php //2.php
namespace Two
class Person{
function __construct(){
echo 'I am tow!
';
}
}
<?php
namespace New;
require_once './2.php';
new Person(); //报错,(当前空间)找不到Person;
new \Person(); //报错,(公共空间)找不到Person;
new \Two\Person(); //输出 I am tow!;
4. 接下来探讨use关键字的具体应用:在使用use进行引用后,后续代码中的类名可以进行简写处理。
namespace School\Parents;
class Man{
function __construct(){
echo 'Listen to teachers!
';
}
}
namespace School\Teacher;
class Person{
function __construct(){
echo 'Please study!
';
}
}
namespace School\Student;
class Person{
function __construct(){
echo 'I want to play!
';
}
}
new Person(); //输出I want to play!
new \School\Teacher\Person(); //输出Please study!
new Teacher\Person(); //报错
----------
use School\Teacher;
new Teacher\Person(); //输出Please study!
----------
use School\Teacher as Tc;
new Tc\Person(); //输出Please study!
----------
use \School\Teacher\Person;
new Person(); //报错
----------
use \School\Parent\Man;
new Man(); //报错
期望上述内容能对各位PHP程序员的开发工作产生积极帮助。