如果我们在一个命名空间里面使用其他空间的成员的时候,如果使用完全限定名称,就会导致这类成员的前缀太长了。为了解决这样的问题,就可以先将需要的类导入到当前空间。use最前面有没有反斜杠都可以,默认就是从全局空间找。
空间的导入分为两类:
空间的整体导入:
说明:如果是整体导入,需要导入之后取别名再使用,如果没有取别名,默认以空间最后的成员为别名。
<?php namespace itbull\php; require_once '9.fullprefix_namespace.php'; use itbull\web; //没有取别名,默认就是web new web\Beauty(); ?>
<?php namespace itbull\php; require_once '9.fullprefix_namespace.php'; use itbull\web as w; //没有取别名,默认就是web new w\Beauty(); ?>
9.fullprefix_namespace.php
<?php namespace itbull\web; class Beauty { public function __construct(){ echo 'itbull\web'; } } ?>
单独导入类、函数、常量:
说明:在php5.6版本之前只能导入类,php5.6之后,允许导入函数、常量。
导入类:use 空间\类
导入函数:use function 空间\函数名
导入常量:use const 空间\变量名
演示代码:
<?php namespace itbull\php; $a = "666"; require_once '9.fullprefix_namespace.php'; //导入类 use itbull\web\Beauty; echo $a; //调用itbull\php这个命名空间 //导入函数 use function itbull\web\myfunc; //导入常量 use const itbull\web\ROOT; //使用导入的类; new Beauty(); //使用导入的函数; myfunc(); //使用导入的常量; echo $a; //调用itbull\php这个命名空间 echo ROOT;
使用别名,下面的输出和上面是一样的:
<?php namespace itbull\php; require_once '9.fullprefix_namespace.php'; //导入类 use itbull\web\Beauty as B; //导入函数 use function itbull\web\myfunc as m; //导入常量 use const itbull\web\ROOT as R; //使用导入的类; new B(); //使用导入的函数; m(); //使用导入的常量; echo R;
9.fullprefix_namespace.php
<?php namespace itbull\web; class Beauty { public function __construct(){ echo 'itbull\web<br>'; } } function myfunc(){ echo 'function1<br>'; } const ROOT='localhost/0408'; ?>注意:use是全局的,所以最前面加不加"/"都可以,除了use里面的代码,在namespace下面的代码都属于当前namespace命名空间。