Using Namespaces in PHP 5 - Tying a PHP class to a namespace with the namespace keyword (
Page 3 of 4 )
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:
// example on using the 'namespace' keyword to tied up a class to a particular namespace
namespace UserManager::CMS;
class User{
private $firstName;
private $lastName;
private $email;
public function __construct($firstName,$lastName,$email){
if(!$firstName||strlen($firstName)>32){
throw new Exception('Invalid First Name parameter!');
}
if(!$lastName||strlen($lastName)>32){
throw new Exception('Invalid Last Name parameter!');
}
if(!$email||!preg_match("/^.+@.+..+$/",$email)){
throw new Exception('Invalid Email parameter!');
}
$this->firstName=$firstName;
$this->lastName=$lastName;
$this->email=$email;
}
// get user's first name
public function getFirstName(){
return $this->firstName;
}
// get user's last name
public function getLastName(){
return $this->lastName;
}
// get user's email
public function getEmail(){
return $this->email;
}
}
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.
Jump ahead and read the next few lines. We're almost finished!