PHP命名空间的概念与使用

命名空间在其它编程语言中其名称不尽相同,但其核心慨念都是自定义一个存储空间。避免类名重复系统无法判断该执行哪一个类或是哪一个函数。

举例说明下。我先创建test这个文件夹在其当前目录下再创建一个index.php文件这个作为调用类的主文件。

然后,在test文件夹下创建两个php文件 blog.php  web.php  。

blog.php  文件代码如下                                                                        

<?php                                                                                        

class Test{

public function index(){

 

       return "这是blog。php文件下的index方法";

 

}

}

?>

web.php文件下的代码

<?php                                                                                        

class Test{

public function index(){

 

       return "这是blog。php文件下的index方法";

 

}

}

主文件index.php下调用这两个类

<?php

require 'test/blog.php';

require 'test/web.php';

$res=new Test();

$reu=$res->index()

echo $reu;

向浏览器输出将报错。因为类名重复了 这时就需要自定义命名空间 命名空间根据自身需要选取,没有特定的规则限制

<?php

namespace Test\haha;自定义命名空间。

 

?>

主文件下的调用  

use \Test\haha as ab;  引入命名空间 并取别名

 

$res=new ab\Test();

$reu=$res->index();

echo $reu;

 

 

 

?>

命名空间的使用到此结束

 

?>

posted @ 2017-03-13 11:58  卜过如此  阅读(288)  评论(0编辑  收藏  举报