您的位置:首页 > 编程语言 > PHP开发

PHP5.6对命名空间的扩展,use可以导入函数与常量空间

2017-06-06 19:56 645 查看
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 Demo1\test1;  //此处的use是从全局开始的,所以第一个\是可以省略的
use function Demo1\test;

class test1
{
private $name = 'bigmax';
public function getName(){
return $this->name;
}
}

function test($n,$m){
return $n+$m;
}

echo (new namespace\test1)->getName();//这里指的是当前命名空间demo2下的test1
echo '<hr>';
echo (new test1)->getName(); //这里指的是引入的Demo1\test1

echo test(4,5); //非限定
echo '<hr>';
echo \Demo1\test(4,5); //完全限定  可以使用use关键字,来简化这种导入

/**
* 总结,当我们导入的类,与当前脚本中的类重名的时候,如果你直接使用非限定名称来访问类的话呢,ps:限定名称是指有命名空间前缀
* 会默认将当前导入的类名称的前缀,添加到当前的非限定类上,也就是上面的 (new test1)
* 如果你想访问当前脚本中的同名类呢,要加入namespace\  ,否则你就访问不到了
*
*
* 从php5.6开始,不仅仅可以导入类,还可以导入函数、常量
* use funcion My\Full\functionName;
*
* use const My\Full\CONSTANT;
*
* 当类被赋予namespace的时候,比如demo1\test1,那么这个test1就不是全局的了,他是属于空间demo1下面了
* 而当前的test1,他是全局的
*
*
*
*
*
*
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  php