在PHP中,如果命名空间字符串过长时,我们就使用use来相应的缩短命名空间。这也是use在PHP中的作用。下面我们就为大家介绍一下PHP中use的用法。

推荐教程:PHP视频教程

1、new类时,最前面无需用反斜杠。此外,use后没有as时,缩短的命名空间默认为最后一个反斜杠后的内容。

namespace animal\dog;class Life{ function __construct(){  echo 'dog life!'; }}namespace animal\cat;class Life{ function __construct(){  echo 'cat life!'; }}new Life(); //按照代码执行顺序,这里默认animal\cat这个命名空间new \animal\dog\Life(); //Ause animal\dog; //anew dog\Life(); //Buse animal\dog as d; //bnew d\Life();

  通过A、B行代码比较,需要注意:

  使用use后,new类时,最前面没有反斜杠。

  没使用use时,命名空间最前面有反斜杠

  通过a、b行代码比较,可以理解:

  use后没有as时,缩短的命名空间默认为最后一个反斜杠后的内容。如上的:

use animal\dog;

相当于

use animal\dog as dog;

2.namespace后面不建议加类名,但use后可以。

//name.phpnamespace animal\dog;class Life{ function __construct(){  echo 'dog life!'; }}namespace animal\cat;class Life{ function __construct(){  echo 'cat life!'; }}use animal\dog\Life as dog; new dog();

  如上所示,use后加上类名后,就相当于把类改了个名称:由Life改为dog了。

  上面不用as dog就会报错:

 Fatal error:  Cannot use animal\dog\Life as Life because the name is already in use

  因为cat下也有个一样名称的Life类。

  可以理解为,使用use后,这个昵称对应的类只能归当前命名空间占有,其它命名空间下不允许存在该类。

//name.phpnamespace animal\dog;class Life{ function __construct(){  echo 'dog life!'; }}class Dog{ function __construct(){  echo 'dog in dog!'; }}namespace animal\cat;// class Dog{// function __construct(){//  echo 'dog in cat!';//  }// }class Life{ function __construct(){  echo 'cat life!'; }}use animal\dog; new dog\Dog();

如上,使用了

 use animal\dog;  cat

  通过上面代码,我想使用use的目的效果(缩短命名空间名称)就很明显了。

简单总结一下:

  use就是起小名的作用,不论写起来还是说起来都可以省不少事儿。

更多相关文章

  1. PHP——命名空间(namespace)使用详细介绍
  2. PHP在引号前面添加反斜杠及去除反斜杠的办法
  3. PHP 核心特性之命名空间
  4. PHP如何获取不带命名空间的类名
  5. 浅析PHP类的自动加载和命名空间
  6. 数据结构--时间复杂度与空间复杂度
  7. 当给出%宽度时,表的主体减少了Head的col 1空间的总空间
  8. 如何在不制作正确的浮动包装的情况下填充左右浮动之间的空间?
  9. div底部随机5 px空间

随机推荐

  1. 基于百度地图API的Android公交换乘导航
  2. Android API Level对应Android版本一览表
  3. Unable to resolve target 'android-5'
  4. USB UMS MTP设置过程 (二) UsbDeviceManage
  5. Android(安卓)Launcher研究
  6. ConstraintLayout 使用可视化的方式来编
  7. Android(安卓)Input Event Dispatching
  8. Android(安卓)9.0 HTTP请求报错
  9. android下的jni
  10. StevGuo系列文章翻译之Talking about And