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.

PHP namespaces support
three kinds of aliasing or importing: aliasing a class name, aliasing an interface name,
and aliasing a namespace name.
Note that importing a function or constant is not supported.

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

Exemplo #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;

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

Exemplo #2 importing/aliasing with the use operator, multiple use statements combined

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:

Exemplo #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 12 notes

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:

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.