php namespace的使用方法

来源:互联网 发布:手机单机版进销存软件 编辑:程序博客网 时间:2024/06/05 22:51

最近总结了下php的命名空间的使用方法

1.为什么使用命名空间 

解决同名的类引起的冲突

2.使用 

定义了3个相同的class的类的文件如下:

 1.php

<?phpnamespace app\aaa;Class Sam{public function test(){echo "this is test for namespace 11111111";}}?>
2.php

<?phpnamespace app\bbb;Class Sam{public function test(){echo "this is test for namespace 222222222";}}?>

3.php

<?phpClass Sam{public function test(){echo "this is test for namespace 333333333";}}?>

接下来我们把这个三个文件包含到index.php中来进行调用

<?phprequire_once('1.php');require_once('2.php');require_once('3.php');$a = new app\aaa\Sam();$a->test();$b = new app\bbb\Sam();$b->test();$c = new \Sam();$c->test();?>
输出:

this is test for namespace 11111111this is test for namespace 222222222this is test for namespace 333333333

全局调用的时候要注意当index.php本身定义了namespace的时候:

<?phpnamespace app\controllers;require_once('1.php');require_once('2.php');require_once('3.php');$a = new app\aaa\Sam();$a->test();$b = new app\bbb\Sam();$b->test();$c = new \Sam(); //引入顶级空间下的Sam类$c->test();?>



上面的调用就会出错了:

Fatal error: Class 'app\controllers\app\aaa\Sam' not found in index.php
做成修改:

<?phpnamespace app\controllers;require_once('1.php');require_once('2.php');require_once('3.php');//要以 '\' 根命名空间开头$a = new \app\aaa\Sam();引入名称空间aaa下的Sam类$a->test();$b = new \app\bbb\Sam();引入名称空间bbb下的Sam类$b->test();$c = new \Sam();$c->test();?>

输出:

this is test for namespace 11111111this is test for namespace 222222222this is test for namespace 333333333

使用use来进行调用

index.php

<?phpnamespace app\controllers;require_once('1.php');require_once('2.php');require_once('3.php');use app\aaa;use app\bbb;$a = new aaa\Sam();$a->test();$b = new bbb\Sam();$b->test();$c = new \Sam();$c->test();?>


<?phpnamespace app\controllers;//命名空间名字跟真实的路径没有任何关系require_once('1.php');require_once('2.php');require_once('3.php');use app\aaa\Sam;use app\bbb\Sam as b; //这个时候要用别名来代替 不能下面的new Sam()会有俩个$a = new Sam();$a->test();$b = new b();$b->test();$c = new \Sam();$c->test();?>

use的namespace这里不用考虑根路径  namespace后面可以加一个类名也可以不加。 加类名了下面new的时候就不用再带路径了,不加类名,new的时候要带namespace最后的一个路径。还能用as 别名的方法在有冲突的时候。


那些框架当中php 的 use 关键字并不是立刻导入所use的类,它只是声明某类的完整类名(命名空间::类标示符),而后你在上下文中使用此类时系统才会根据 use 声明获取此类的完整类名 然后利用自动加载机制进行载入。


参考文章:
http://www.jianshu.com/p/967df0c5f516
https://my.oschina.net/sallency/blog/613034





原创粉丝点击