php 命名空间详解

来源:互联网 发布:mac如何更新软件 编辑:程序博客网 时间:2024/06/05 06:49

众所周知 命名空间 是php5.3 带来的新特性 可以帮我们解决在工程量大时 类命名重复的问题 下面 我就来分享一下 我对命名空间的理解

首先我们创建三个php文件在同一个文件夹 分别为 index.php test1.php test2.php

test1.php 的内容如下

<?phpclass  test{    function say()    {        echo 'this is test1 ';        echo "<br/>";    }}

test2.php 的内容如下

<?phpclass test{    function say()    {        echo 'this is test2 ';        echo "<br/>";    }}

index.php 的内容如下

<?phprequire_once('test1.php');require_once('test2.php');

现在当我们调用 index.php 时我们会发现一个错误

这里写图片描述

php提示我们不能声明 test2.php 的 test类


这是为什么呢 其实是因为 test2.php 中的 test类 和 test1.php 中的类重名了 系统不知道该调用哪一个

正是为了解决这一个问题 所以 php5.3 引入了 命名空间这一新特性

现在我们为 test1.php 加上命名空间

<?phpnamespace space\test1;class  test{    function say()    {        echo 'this is test1 ';        echo "<br/>";    }}

同理 test2.php

<?phpnamespace space\test2;class test{    function say()    {        echo 'this is test2 ';        echo "<br/>";    }}

现在我们在调用 index.php 我们就会发现错误不见了


这是为什么呢 其实是因为 我们加了 namespace 命名空间以后 系统会自动识别 test1.php 的test类 是space\test1里面的 而test2.php 的test类 是space\test2里面的 他们是不同的


下面我们在 index.php 里加上几行代码测试一下

<?phprequire_once('test1.php');require_once('test2.php');$test1 = new \space\test1\test();$test2 = new \space\test1\test();$test1->say();$test2->say();


运行后得到

这里写图片描述


我们会发现 运行完美成功


但是每次 初始化 new 一个实例出来的时候 我们都要 写上 $test1 = new \space\test1\test(); 这样的一大长串 是不是有一点不够简洁 正是因为这个原因 php 又为我们 提供了 use 关键字

use 的作用是设定我们默认使用的命名空间

<?phprequire_once('test1.php');require_once('test2.php');use space\test1\test;$test1 = new test();$test1->say();


然后 我们在 访问 index.php


这里写图片描述

完美 果然 把 test1.php 中的 test类 给实例化出来了


这时候 想必 肯定 会有人 问 那 test2.php 中的 test类 我们怎么实现出来呢


是像下面这样来实现吗

这里写图片描述

大家光看照片 就知道 肯定不能 这样来实现了 因为编译器 已经报错了


因为这样的话 系统又会像没有加命名空间一样 不知道该调用哪一个 test类了


为了 解决 这个问题 所以 php 又给我们 推出了 一个 和 use 关键字连用的关键字 as


as的用法是为命名空间取一个别名

<?phprequire_once('test1.php');require_once('test2.php');use space\test1\test;use space\test2\test as test2;$test1 = new test();$test2 = new test2();$test1->say();$test2->say();

现在我们在调用 index.php

这里写图片描述

完美运行