For the purposes of this example, we will define two almost identical code blocks; the only difference is their namespace:
lib1.php:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<br /> &lt;?php<br /> // application library 1<br /> namespace AppLib1;<br /> const MYCONST = 'AppLib1MYCONST';<br /> function MyFunction() {<br /> return __FUNCTION__;<br /> }<br /> class MyClass {<br /> static function WhoAmI() {<br /> return __METHOD__;<br /> }<br /> }<br /> ?&gt;<br /> |
lib2.php:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
&lt;span style=&quot;text-align: justify;&quot;&gt;&lt;?php&lt;/span&gt;&lt;/pre&gt;<br /> // application library 2<br /> namespace AppLib2;<br /> const MYCONST = 'AppLib2MYCONST';<br /> function MyFunction() {<br /> return __FUNCTION__;<br /> }<br /> class MyClass {<br /> static function WhoAmI() {<br /> return __METHOD__;<br /> }<br /> }<br /> ?&gt;<br /> |
There is a little PHP terminology to understand before we begin?
Fully-qualified name
Any PHP code can refer to a fully-qualified name ? an identifier starting with the namespace backslash separator, e.g. AppLib1MYCONST, AppLib2MyFunction(), etc.
Fully-qualified names have no ambiguity. The initial backslash operates in a similar way to a file path; it signifies the ?root? global space. If we implemented a different MyFunction() in our global space, it could be called from lib1.php or lib2.php using MyFunction().
Fully-qualified names are useful for one-off function calls or object initialization. However, they can become impractical when you are making lots of calls. As we will discover below, PHP offers other options to save us from namespace typing cramps.
Qualified name
An identifier with at least one namespace separator, e.g. Lib1MyFunction().
Unqualified name
An identifier without a namespace separator, e.g. MyFunction().