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:
<?php
namespace 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 ERROR
I 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:
<?php
require 'myclass.php';
use my%space%myclass;
$x = new myclass;
//...
?>
it will work fine.
I hope this reduces the number of prematurely bald people.
Namespaces verwenden: Importieren/Aliase
(PHP 5 >= 5.3.0)
Die Möglichkeit, auf vollständig qualifizierte Namen mit einem Alias (Importieren) zuzugreifen, ist ein wichtiges Feature von Namespaces. Dies ist ähnlich wie die Möglichkeit von Unix-basierten Dateisystemen einen symbolischen Link auf eine Datei oder ein Verzeichnis anzulegen.
PHP-Namespaces unterstützen drei Arten von Aliasen oder Importen: Einen Alias für einen Klassennamen, einen Alias für einen Interfacenamen und einen Alias für einen Namespace. Beachten Sie, dass das importieren einer Funktion oder Konstanten nicht unterstützt wird.
Ein Alias wird in PHP mittels des use-Operators angelegt. Hier ein Beispiel, welches alle drei Arten von Importen zeigt:
Beispiel #1 Importieren/Aliase mit dem use-Operator
<?php
namespace foo;
use My\Full\Classname as Another;
// dies ist das gleiche wie use My\Full\NSname as NSname
use My\Full\NSname;
// importiert eine globale Klasse
use ArrayObject;
$obj = new namespace\Another; // erzeugt ein Objekt der Klasse foo\Another
$obj = new Another; // erzeugt ein Objekt der Klasse My\Full\Classname
NSname\subns\func(); // ruft die Funktion My\Full\NSname\subns\func auf
$a = new ArrayObject(array(1)); // erzeugt ein Objekt der Klasse ArrayObject
// ohne das "use ArrayObject" wäre ein Objekt der Klasse foo\ArrayObject erzeugt worden
?>
PHP unterstützt zusätzlich auch eine komfortable Kurzsyntax, mit der mehrere use-Ausdrücke in der gleichen Zeile erscheinen können.
Beispiel #2 Importieren/Aliase mit dem use-Operator, mehrere use-Ausdrücke kombiniert
<?php
use My\Full\Classname as Another, My\Full\NSname;
$obj = new Another; // erzeugt ein Objekt der Klasse My\Full\Classname
NSname\subns\func(); // ruft die Funktion My\Full\NSname\subns\func auf
?>
Importieren wird zur Kompilierungszeit ausgeführt und hat daher keinen Einfluss auf dynamische Klassen-, Funktions- oder Konstantennamen.
Beispiel #3 Importieren und dynamische Namen
<?php
use My\Full\Classname as Another, My\Full\NSname;
$obj = new Another; // erzeugt ein Objekt der Klasse My\Full\Classname
$a = 'Another';
$obj = new $a; // erzeugt ein Objekt der Klasse Another
?>
Zusätzlich beeinflusst das Importieren nur unqualifizierte und qualifizierte Namen. Vollständig qualifizierte Namen sind absolut und werden von Importen nicht beeinflusst.
Beispiel #4 Importieren und vollständig qualifizierte Namen
<?php
use My\Full\Classname as Another, My\Full\NSname;
$obj = new Another; // erzeugt ein Objekt der Klasse My\Full\Classname
$obj = new \Another; // erzeugt ein Objekt der Klasse Another
$obj = new Another\thing; // erzeugt ein Objekt der Klasse My\Full\Classname\thing
$obj = new \Another\thing; // erzeugt ein Objekt der Klasse Another\thing
?>
Gültigkeitsbereiche für Importe
Das Schlüsselwort use muss im äußersten Gültigkeitsbereich (dem globalen Gültigkeitsbereich) oder innerhalb einer Namespace-Deklaration angegeben werden. Das ist darin begründet, dass Importe zur Kompilierungszeit und nicht zur Laufzeit durchgeführt werden und daher nicht in einem anderen Gültigkeitsbereich liegen dürfen. Das folgende Beispiel zeigt eine ungültige Verwendung des use-Schlüsselwortes:
Beispiel #5 Ungültige Importregel
<?php
namespace Languages;
class Greenlandic
{
use Languages\Danish;
...
}
?>
Hinweis:
Importregeln sind auf Dateibasis gültig, das heißt eine eingebundene Datei wird NICHT die Importregeln der einbindenden Datei erben.
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.
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:
<?php
use 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".
Note that you can not alias global namespace:
use \ as test;
echo test\strlen('');
won't work.
The "use" keyword can not be declared inside the function or method. It should be declared as global, after the "namespace" as:
<?php
namespace mydir;
// works perfectly
use 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;
}
}
?>
(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.php
namespace foo;
class bar
{
public function __toString ()
{
return 'foo\bar\__toString()';
}
}
?>
<?php
// foo/bar/MyClass.php
namespace foo/bar;
class MyClass
{
public function __toString ()
{
return 'foo\bar\MyClass\__toString()';
}
}
?>
In another namespace, you can do:
<?php
namespace 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()
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.
Because imports happen at compile time, there's no polymorphism potential by embedding the use keyword in a conditonal.
e.g.:
<?php
if ($objType == 'canine') {
use Animal\Canine as Beast;
}
if ($objType == 'bovine') {
use Animal\Bovine as Beast;
}
$oBeast = new Beast;
$oBeast->feed();
?>
