PHP 7.1.0 Released

## Using namespaces: Aliasing/Importing

(PHP 5 >= 5.3.0)

The ability to refer to an external fully qualified name with an alias, or importing, is an important feature of namespaces. This is similar to the ability of unix-based filesystems to create symbolic links to a file or to a directory.

All versions of PHP that support namespaces support three kinds of aliasing or importing: aliasing a class name, aliasing an interface name, and aliasing a namespace name. PHP 5.6+ also allows aliasing or importing function and constant names.

In PHP, aliasing is accomplished with the use operator. Here is an example showing all 5 kinds of importing:

Example #1 importing/aliasing with the use operator

 <?phpnamespace foo;use My\Full\Classname as Another;// this is the same as use My\Full\NSname as NSnameuse My\Full\NSname;// importing a global classuse 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; // instantiates object of class foo\Another$obj = new Another; // instantiates object of class My\Full\ClassnameNSname\subns\func(); // calls function My\Full\NSname\subns\func$a = new ArrayObject(array(1)); // instantiates object of class ArrayObject// without the "use ArrayObject" we would instantiate an object of class foo\ArrayObjectfunc(); // calls function My\Full\functionNameecho CONSTANT; // echoes the value of My\Full\CONSTANT?>  Note that for namespaced names (fully qualified namespace names containing namespace separator, such as Foo\Bar as opposed to global names that do not, such as FooBar), the leading backslash is unnecessary and not recommended, as import names must be fully qualified, and are not processed relative to the current namespace. PHP additionally supports a convenience shortcut to place multiple use statements on the same line Example #2 importing/aliasing with the use operator, multiple use statements combined  <?phpuse My\Full\Classname as Another, My\Full\NSname;$obj = new Another; // instantiates object of class My\Full\ClassnameNSname\subns\func(); // calls function My\Full\NSname\subns\func?> 

Importing is performed at compile-time, and so does not affect dynamic class, function or constant names.

Example #3 Importing and dynamic names

 <?phpuse My\Full\Classname as Another, My\Full\NSname;$obj = new Another; // instantiates object of class My\Full\Classname$a = 'Another';$obj = new$a;      // instantiates object of class Another?> 

In addition, importing only affects unqualified and qualified names. Fully qualified names are absolute, and unaffected by imports.

Example #4 Importing and fully qualified names

 <?phpuse 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?> 

### Scoping rules for importing

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

 <?phpnamespace Languages;class Greenlandic{    use Languages\Danish;    ...}?> 

Nota:

Importing rules are per file basis, meaning included files will NOT inherit the parent file's importing rules.

### User Contributed Notes 17 notes

41
k at webnfo dot com
3 years ago
 Note that you can not alias global namespace:use \ as test;echo test\strlen('');won't work. 
23
anon
2 years ago
 The <?php use ?> statement does not load the class file. You have to do this with the <?php require ?> statement or by using an autoload function. 
19
cl
3 years ago
 Something that is not immediately obvious, particular with PHP 5.3, is that namespace resolutions within an import are not resolved recursively.  i.e.: if you alias an import and then use that alias in another import then this latter import will not be fully resolved with the former import.For example:use \Controllers as C;use C\First;use C\Last;Both the First and Last namespaces are NOT resolved as \Controllers\First or \Controllers\Last as one might intend. 
kelerest123 at gmail dot com
1 year ago
 For the fifth example (example #5):When in block scope, it is not an illegal use of use keyword, because it is used for sharing things with traits. 
20
x at d dot a dot r dot k dot REMOVEDOTSANDTHIS dot gray dot org
3 years ago
 You are allowed to "use" the same resource multiple times as long as it is imported under a different alias at each invocation.For example:<?phpuse Lend;use Lend\l1;use Lend\l1 as l3;use Lend\l2;use Lend\l1\Keller;use Lend\l1\Keller as Stellar;use Lend\l1\Keller as Zellar;use Lend\l2\Keller as Dellar;...?>In the above example, "Keller", "Stellar", and "Zellar" are all references to "\Lend\l1\Keller", as are "Lend\l1\Keller", "l1\Keller", and "l3\Keller". 
me at ruslanbes dot com
8 months ago
 Note the code use ns1\c1 may refer to importing class c1 from namespace ns1 as well as importing whole namespace ns1\c1 or even import both of them in one line. Example:<?phpnamespace ns1;class c1{}namespace ns1\c1;class c11{}namespace main;use ns1\c1;$c1 = new c1();$c11 = new c1\c11();var_dump($c1); // object(ns1\c1)#1 (0) { }var_dump($c11); // object(ns1\c1\c11)#2 (0) { } 
ultimater at gmail dot com
2 months ago
 Note that "use" importing/aliasing only applies to the current namespace block.<?phpnamespace SuperCoolLibrary{    class Meta    {        static public function getVersion()        {            return '2.7.1';        }    }}namespace{    use SuperCoolLibrary\Meta;    echo Meta::getVersion();//outputs 2.7.1}namespace{    echo Meta::getVersion();//fatal error}?>To get the expected behavior, you'd use:class_alias('SuperCoolLibrary\Meta','Meta'); 
19
c dot 1 at smithies dot org
5 years ago
 If you are testing your code at the CLI, note that namespace aliases do not work!(Before I go on, all the backslashes in this example are changed to percent signs because I cannot get sensible results to display in the posting preview otherwise. Please mentally translate all percent signs henceforth as backslashes.)Suppose you have a class you want to test in myclass.php:<?phpnamespace my%space;class myclass { // ...}?>and you then go into the CLI to test it. You would like to think that this would work, as you type it line by line:require 'myclass.php';use my%space%myclass; // should set 'myclass' as alias for 'my%space%myclass'$x = new myclass; // FATAL ERRORI believe that this is because aliases are only resolved at compile time, whereas the CLI simply evaluates statements; so use statements are ineffective in the CLI.If you put your test code into test.php:<?phprequire 'myclass.php';use my%space%myclass;$x = new myclass;//...?>it will work fine.I hope this reduces the number of prematurely bald people. 
Anonymous
3 years ago
 The last example on this page shows a possibly incorrect attempt of aliasing, but it is totally correct to import a trait \Languages\Languages\Danish. 
dominic_mayers at yahoo dot com
2 months ago
 To clarify the distinction between inserting a trait in a class and importing a trait in a namespace, here is an example where we first import and then insert a trait. <?phpnamespace ns1;trait T {  static $a = "In T";}namespace ns2;use ns1\T; // Importing the name of trait ns1\T in the namespace ns2class C { use T; // Inserting trait T in the class C, making use of the imported name. } namespace main;use ns2\C;echo C::$a; // In T; 
dominic_mayers at yahoo dot com
2 months ago
 The keyword "use" has been recycled for three distinct applications: 1- to import/alias classes, traits, constants, etc. in namespaces, 2- to insert traits in classes, 3- to inherit variables in closures. This page is only about the first application: importing/aliasing. Traits can be inserted in classes, but this is different from importing a trait in a namespace, which cannot be done in a block scope, as pointed out in example 5. This can be confusing, especially since all searches for the keyword "use" are directed to the documentation here on importing/aliasing. 
thinice at gmail.com
6 years ago
 Because imports happen at compile time, there's no polymorphism potential by embedding the use keyword in a conditonal.e.g.:<?phpif ($objType == 'canine') { use Animal\Canine as Beast;}if ($objType == 'bovine') {  use Animal\Bovine as Beast;}$oBeast = new Beast;$oBeast->feed();?> 
-1
samuel dot roze at gmail dot com
4 years ago
 (All the backslashes in namespaces are slashes because I can't figure out how to post backslashes here.)You can have the same "use" for a class and a namespace. For example, if you have these files:<?php// foo/bar.phpnamespace foo;class bar{    public function __toString ()    {        return 'foo\bar\__toString()';    }}?><?php// foo/bar/MyClass.phpnamespace foo/bar;class MyClass{    public function __toString ()    {        return 'foo\bar\MyClass\__toString()';    }}?>In another namespace, you can do:<?phpnamespace another;require_once 'foo/bar.php';require_once 'foo/bar/MyClass.php';use foo/bar;$bar = new bar();echo$bar."\n";$class = new bar/MyClass();echo$class."\n";?>And it will makes the following output:foo\bar\__toString()foo\bar\MyClass\__toString() 
-3
nsdhami at live dot jp
6 years ago
 The "use" keyword can not be declared inside the function or method. It should be declared as global, after the "namespace" as:<?phpnamespace mydir;// works perfectlyuse mydir/subdir/Class1 as Class1;function fun1(){    // Parse error: syntax error, unexpected T_USE    use mydir/subdir/Class1 as Class1;}class Class2{    public function fun2()    {        // Parse error: syntax error, unexpected T_USE        use mydir/subdir/Class1 as Class1;    }}?> 
-4
sernuzh at gmail dot com
1 year ago
 You'll get here the Fatal error: Cannot declare class others\name because the name is already in useSo you can't get two classes <name> inside one namespace<?phpnamespace my {class name {public function __construct(){echo 'my_namespace_object';}}}namespace others{use my\name;class name {public function __construct(){echo 'others_namespace_object';}}$newObject = new name();}?>  -21 Jan Tvrdk 5 years ago  Importing and aliasing an interface name is also supported.  -25 Dr. Gianluigi &#34;Zane&#34; Zanettini 1 year ago  I was attempting to use something like this:<?phpuse$my_variable_namespace?>This is not supported. I did this instead:<?phpif(..)    use My\First\Namespace;else    use My\Other\Namespace;?>