In a file named lib1.php, we will define a constant, a function, and a class within the AppLib1 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 /> |
We can now include this code in another PHP file, e.g.
myapp.php
1 2 3 4 5 6 7 8 |
<br /> &lt;?php<br /> header('Content-type: text/plain');<br /> require_once('lib1.php');<br /> echo AppLib1MYCONST . &quot;n&quot;;<br /> echo AppLib1MyFunction() . &quot;n&quot;;<br /> echo AppLib1MyClass::WhoAmI() . &quot;n&quot;;<br /> ?&gt;<br /> |
No namespace is defined in myapp.php so the code exists in the global space. Any direct reference to MYCONST, MyFunction or MyClass will fail because they exist in the AppLib1 namespace. To call code in lib1.php, we can add a prefix of AppLib1 to define fully-qualified names. The following result is output when we load myapp.php:
1 2 3 4 |
<br /> AppLib1MYCONST<br /> AppLib1MyFunction<br /> AppLib1MyClass::WhoAmI<br /> |
Fully-qualified names can become quite long and there are few obvious benefits over defining long class names such as App-Lib1-MyClass. Therefore, in the next article, we will discuss aliasing and take a closer look at how PHP resolves namespace names.