User Contributed Notes 20 notes

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.

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.

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:

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();}?>