(PHP 5 >= 5.3.0, PHP 7)
锟斤拷锟斤拷通锟斤拷锟斤拷锟斤拷锟斤拷锟矫伙拷锟斤拷锟解部锟斤拷锟斤拷全锟睫讹拷锟斤拷锟狡o拷锟斤拷锟斤拷锟斤拷锟秸硷拷锟揭伙拷锟斤拷锟揭拷锟斤拷锟斤拷锟斤拷锟斤拷械锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟� unix 锟侥硷拷系统锟叫匡拷锟皆达拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟侥硷拷锟斤拷目录锟侥凤拷锟斤拷锟斤拷锟接★拷
锟斤拷锟斤拷支锟斤拷锟斤拷锟斤拷锟秸硷拷锟絇HP锟芥本支锟斤拷锟斤拷锟街憋拷锟斤拷锟斤拷锟诫方式锟斤拷为锟斤拷锟斤拷锟斤拷使锟矫憋拷锟斤拷锟斤拷为锟接匡拷使锟矫憋拷锟斤拷锟斤拷为锟斤拷锟斤拷锟秸硷拷锟斤拷锟斤拷使锟矫憋拷锟斤拷锟斤拷PHP 5.6锟斤拷始锟斤拷锟斤拷锟诫函锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷为锟斤拷锟斤拷锟斤拷锟矫憋拷锟斤拷锟斤拷
锟斤拷PHP锟叫o拷锟斤拷锟斤拷锟斤拷通锟斤拷锟斤拷锟斤拷锟斤拷 use 锟斤拷实锟街碉拷. 锟斤拷锟斤拷锟斤拷一锟斤拷使锟斤拷锟斤拷锟叫匡拷锟杰碉拷锟斤拷锟街碉拷锟诫方式锟斤拷锟斤拷锟接o拷
Example #1 使锟斤拷use锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷/使锟矫憋拷锟斤拷
<?php
namespace foo;
use My\Full\Classname as Another;
// 锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟� use My\Full\NSname as NSname 锟斤拷同
use My\Full\NSname;
// 锟斤拷锟斤拷一锟斤拷全锟斤拷锟斤拷
use ArrayObject;
// importing a function (PHP 5.6+)
use function My\Full\functionName;
// aliasing a function (PHP 5.6+)
use function My\Full\functionName as func;
// importing a constant (PHP 5.6+)
use const My\Full\CONSTANT;
$obj = new namespace\Another; // 实锟斤拷锟斤拷 foo\Another 锟斤拷锟斤拷
$obj = new Another; // 实锟斤拷锟斤拷 My\Full\Classname锟斤拷锟斤拷锟斤拷
NSname\subns\func(); // 锟斤拷锟矫猴拷锟斤拷 My\Full\NSname\subns\func
$a = new ArrayObject(array(1)); // 实锟斤拷锟斤拷 ArrayObject 锟斤拷锟斤拷
// 锟斤拷锟斤拷锟绞癸拷锟� "use \ArrayObject" 锟斤拷锟斤拷实锟斤拷锟斤拷一锟斤拷 foo\ArrayObject 锟斤拷锟斤拷
func(); // calls function My\Full\functionName
echo CONSTANT; // echoes the value of My\Full\CONSTANT
?>
为锟剿简化诧拷锟斤拷锟斤拷PHP锟斤拷支锟斤拷锟斤拷一锟斤拷锟斤拷使锟矫讹拷锟絬se锟斤拷锟�
Example #2 通锟斤拷use锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷/使锟矫憋拷锟斤拷锟斤拷一锟斤拷锟叫帮拷锟斤拷锟斤拷锟絬se锟斤拷锟�
<?php
use My\Full\Classname as Another, My\Full\NSname;
$obj = new Another; // 实锟斤拷锟斤拷 My\Full\Classname 锟斤拷锟斤拷
NSname\subns\func(); // 锟斤拷锟矫猴拷锟斤拷 My\Full\NSname\subns\func
?>
锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷诒锟斤拷锟街达拷械模锟斤拷锟斤拷锟教拷锟斤拷锟斤拷锟斤拷啤锟斤拷锟斤拷锟斤拷锟斤拷苹锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷恰锟�
Example #3 锟斤拷锟斤拷投锟教拷锟斤拷锟�
<?php
use My\Full\Classname as Another, My\Full\NSname;
$obj = new Another; // 实锟斤拷锟斤拷一锟斤拷 My\Full\Classname 锟斤拷锟斤拷
$a = 'Another';
$obj = new $a; // 实锟绞伙拷一锟斤拷 Another 锟斤拷锟斤拷
?>
锟斤拷锟解,锟斤拷锟斤拷锟斤拷锟街挥帮拷锟斤拷锟睫讹拷锟斤拷锟狡猴拷锟睫讹拷锟斤拷锟狡★拷锟斤拷全锟睫讹拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷确锟斤拷锟侥o拷锟绞诧拷锟杰碉拷锟斤拷锟接帮拷臁�
Example #4 锟斤拷锟斤拷锟斤拷锟饺拷薅锟斤拷锟斤拷锟�
<?php
use My\Full\Classname as Another, My\Full\NSname;
$obj = new Another; // instantiates object of class My\Full\Classname
$obj = new \Another; // instantiates object of class Another
$obj = new Another\thing; // instantiates object of class My\Full\Classname\thing
$obj = new \Another\thing; // instantiates object of class Another\thing
?>
The use keyword must be declared in the outermost scope of a file (the global scope) or inside namespace declarations. This is because the importing is done at compile time and not runtime, so it cannot be block scoped. The following example will show an illegal use of the use keyword:
Example #5 Illegal importing rule
<?php
namespace Languages;
class Greenlandic
{
use Languages\Danish;
...
}
?>
Note:
Importing rules are per file basis, meaning included files will NOT inherit the parent file's importing rules.