Namespaces were created as part of PHP 5.3 to solve certain conflicts that can arise when two different classes are given the same name. This situation comes up more commonly than you might think. This four-part series introduces you to using namespaces to solve these and similar issues. It includes copious code examples to enhance your understanding.
The simplest way to tie a PHP class to a specific namespace is by using the “namespace” keyword. Now, returning to the “User” class built in the previous section, if I ever want to link it to a fictional “UserManager::CMS” namespace, then I’d use the keyword in question in the following manner:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
<br /> // example on using the 'namespace' keyword to tied up a class to a particular namespace</p> <p>namespace UserManager::CMS;</p> <p>class User{</p> <p>private $firstName;</p> <p>private $lastName;</p> <p>private $email;</p> <p>public function __construct($firstName,$lastName,$email){</p> <p>if(!$firstName||strlen($firstName)&gt;32){</p> <p>throw new Exception('Invalid First Name parameter!');</p> <p>}</p> <p>if(!$lastName||strlen($lastName)&gt;32){</p> <p>throw new Exception('Invalid Last Name parameter!');</p> <p>}</p> <p>if(!$email||!preg_match(&quot;/^.+@.+..+$/&quot;,$email)){</p> <p>throw new Exception('Invalid Email parameter!');</p> <p>}</p> <p>$this-&gt;firstName=$firstName;</p> <p>$this-&gt;lastName=$lastName;</p> <p>$this-&gt;email=$email;</p> <p>}</p> <p>// get user's first name</p> <p>public function getFirstName(){</p> <p>return $this-&gt;firstName;</p> <p>}</p> <p>// get user's last name</p> <p>public function getLastName(){</p> <p>return $this-&gt;lastName;</p> <p>}</p> <p>// get user's email</p> <p>public function getEmail(){</p> <p>return $this-&gt;email;</p> <p>}</p> <p>}</p> <p> |
As you can see in the previous hands-on example, before including the definition of the previous “User” class, I used the “namespace” keyword to indicate to the PHP interpreter that that specific class must be tied to a hypothetical “UserManager::CMS” namespace, assuming that the class in question will be used within the context of a user-related content management system.
Of course, I created this concrete namespace only for illustrative purposes, but naturally you can use others to suit your personal needs and preferences.
Well, at this point I already showed you how to specify that a sample “User” class must belong to a “UserManager::CMS” namespace, in this way preventing any eventual conflicts with one or more classes that share the same name.
However, the prior example would be incomplete if I didn’t show you how to call this sample class in the context of a PHP script. Thus, in the last section of this tutorial I’m going to code a brand new example for you to dissipate any possible doubts about how to achieve this process in a simple way.