php中use的用法

2020-08-28,

/2020/08/e6421e68.jpg

  在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(); //A
use animal\dog; //a
new dog\Life(); //B
use animal\dog as d; //b
new d\Life();

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

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

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

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

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

use animal\dog;

相当于

use animal\dog as dog;

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

//name.php
namespace 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.php
namespace 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就是起小名的作用,不论写起来还是说起来都可以省不少事儿。

以上就是php中use的用法的详细内容,更多请关注北冥有鱼其它相关文章!

本文转载自【PHP中文网】,希望能给您带来帮助,苟日新、日日新、又日新,生命不息,学习不止。

《php中use的用法.doc》

下载本文的Word格式文档,以方便收藏与打印。