首页 > 编程知识 正文

php 命名空间和use,php命名空间的使用

时间:2023-05-04 01:33:55 阅读:250512 作者:930

php版本 > 5.60


1、解决命名冲突

2、导入类、函数、常量

3、赋予别名



test1.php

namespace Demo1;class test1{ private $name = 'bigboy'; public function getName(){ return $this->name; }}function test($n,$m){ return $n*$m;}


test2.php

namespace Demo2;use Demo1test1; //此处的use是从全局开始的,所以第一个是可以省略的use function Demo1test;class test1{ private $name = 'bigmax'; public function getName(){ return $this->name; }}function test($n,$m){ return $n+$m;}echo (new namespacetest1)->getName();//这里指的是当前命名空间demo2下的test1echo '<hr>';echo (new test1)->getName(); //这里指的是引入的Demo1test1echo test(4,5); //非限定echo '<hr>';echo Demo1test(4,5); //完全限定 可以使用use关键字,来简化这种导入/** * 总结,当我们导入的类,与当前脚本中的类重名的时候,如果你直接使用非限定名称来访问类的话呢,ps:限定名称是指有命名空间前缀 * 会默认将当前导入的类名称的前缀,添加到当前的非限定类上,也就是上面的 (new test1) * 如果你想访问当前脚本中的同名类呢,要加入namespace ,否则你就访问不到了 * * * 从php5.6开始,不仅仅可以导入类,还可以导入函数、常量 * use funcion MyFullfunctionName; * * use const MyFullCONSTANT; * * 当类被赋予namespace的时候,比如demo1test1,那么这个test1就不是全局的了,他是属于空间demo1下面了 * 而当前的test1,他是全局的 * * * * * * */

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。