Namespace aliases are perhaps the most useful construct. Aliases allow us to reference long namespaces using a shorter name.
myapp3.php:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<br /> &lt;?php<br /> use AppLib1 as L;<br /> use AppLib2MyClass as Obj;<br /> header('Content-type: text/plain');<br /> require_once('lib1.php');<br /> require_once('lib2.php');<br /> echo LMYCONST . &quot;n&quot;;<br /> echo LMyFunction() . &quot;n&quot;;<br /> echo LMyClass::WhoAmI() . &quot;n&quot;;<br /> echo Obj::WhoAmI() . &quot;n&quot;;<br /> ?&gt;</p> <p> |
The first use statement defines AppLib1 as ?L?. Any qualified names using ?L? will be translated to ?AppLib1? at compile-time. We can therefore refer to LMYCONST and LMyFunction rather than the fully-qualified name.
The second use statement is more interesting. It defines ?Obj? as an alias for the class ?MyClass? within the AppLib2 namespace. This is only possible for classes ? not constants or functions. We can now use new Obj() or run static methods as shown above.
result:
1 2 3 4 5 6 7 |
</p> <p>view plainprint?<br /> AppLib1MYCONST<br /> AppLib1MyFunction<br /> AppLib1MyClass::WhoAmI<br /> AppLib2MyClass::WhoAmI</p> <p> |