Using Namespaces in PHP 5

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.

Introduction

If you’re an experienced PHP developer, then you’ll surely know that building web applications using the object-oriented paradigm can be a pretty challenging process, at least in the beginning. However, as you master the key concepts that surround the use of this approach, working with classes and objects becomes so familiar that you can start quickly developing more complex PHP programs.

While the learning process looks very educational and even fun, the truth is that things can get more complicated when you begin using third-party classes or even entire development frameworks. For instance, say that you’ve created a neat database abstraction class, called "MySQL," which handles all of your database-related tasks.

So far, this class isn’t conflictive, right? But, this scenario may change for the worse if you decide to use a forum application created by another programmer, which also includes a class named "MySQL." Whenever you try to use the forum’s classes and yours together, it’s possible that the PHP interpreter will complain loudly when it finds that you’re attempting to use two classes that share the same name!

Of course, you can solve this problem by renaming one of the conflictive classes, but sometimes this process can be a true nightmare, or simply a nonviable solution. Nonetheless, not all is lost in this case, because with the release of PHP 5.3, this problem could be easily solved by way of namespaces.

In simple terms, by using this feature it’s possible to specify that one or more PHP classes must belong to a certain namespace, which should avoid a naming conflict between classes like the one described above. In this particular case, you might specify that your MySQL class is valid within a namespace called "general," while the forum’s class would be available in a "forum" namespace.

Understanding how namespaces work in PHP 5 naturally requires much more than simple theory. Therefore, in this group of articles, I’ll be developing for you several code samples, which hopefully will help you learn how to use this helpful feature within your forthcoming PHP applications.

Now it’s time to move past the preliminaries and start digging deeper into the use of namespaces in PHP 5. Let’s begin this educational journey now!

{mospagebreak title=The need to use namespaces in PHP 5}

A good way to start explaining how to utilize namespaces with PHP 5 consists of recreating a simple – yet potentially real — situation, where the name of a given class can be shared by another. In this case, suppose that there’s a class called "User" which stores common user-supplied data, such as first and last names, as well as the corresponding email addresses.

The prototypical signature of a class like the one described above would look like this:


// define ‘User’ class


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;

}

}


Undoubtedly, the signature of the above "User" class is quite easy to grasp, since this class simply stores the full name and the email address of a fictional user on a few properties. In addition, the class implements some accessors, used directly for retrieving the values of these properties when required.

Now that you’ve seen how this sample class has been defined, here’s an example that demonstrates how to use in a concrete case. Take a look at the following code sample, please:

// example on using the previous ‘User’ class without namespaces


try{

// create new instance of ‘User’ class

$user=new User(‘Alejandro’,’Gervasio’,’alejandro@domain.com’);

// display user data

echo ‘First Name: ‘.$user->getFirstName().'<br />';

echo ‘Last Name: ‘.$user->getLastName().'<br />';

echo ‘Email: ‘.$user->getEmail().'<br />';

 

/* displays the following output

First Name: Alejandro

Last Name: Gervasio

Email: alejandro@domain.com

*/

}

catch(Exception $e){

echo $e->getMessage();

exit();

}


Actually, I don’t want to be accused of being too selfish, but as you can see in the previous example, I utilized the "User" class to save my first and last names, as well as my email address as plain class properties. Once that task has been accomplished, these values are echoed to the browser via the respective accessors. That was really simple to code and understand, wasn’t it?

So far, everything looks pretty good here, since this basic class does a decent job, particularly when it comes to handling user-supplied data. However, this seemingly peaceful scenario can turn quickly into a raging storm if I decide to work in conjunction with a third-party content management system, which also includes a class named "User."

How can these classes be used within the same PHP application, without having to waste time renaming one of them?

Well, the answer to that question is simply by using namespaces! With namespaces, it would be possible to specify that one "User" class belongs to a concrete namespace, called for example "General," while the second one would belong to a different namespace, named "CMS." Are you starting to see the benefits of using namespaces? I bet you are!

However, if you’re anything like me, then you’ll want to see how namespaces can be used with some functional PHP code. Therefore, bearing in mind this possibility, in the section to come, I’m going to show you how to utilize the previous "User" class so it can be tied to a predefined namespace.

To learn the full details of how this process will be accomplished, please click on the link that appears below and keep reading.

{mospagebreak title=Tying a PHP class to a namespace with the namespace keyword}

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!

{mospagebreak title=Working with a PHP class tied to a specific namespace}

Provided that in the previous section you learned how to link a basic "User" class to a specific namespace, the next thing that I’m going to show you in this tutorial will be how to call an instance of that class within a PHP script.

The following script demonstrates in a simple way how to work with a "$user" object whose originating class has been tied previously to a "UserManager::CMS" namespace. Have a look at it, please:


<?php


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;

}

}


try{

// create new instance of ‘User’ class by using the specified namespace

$user=new UserManager::CMS::User(‘Alejandro’,’Gervasio’,’alejandro@domain.com’);

// display user data

echo ‘First Name: ‘.$user->getFirstName().'<br />';

echo ‘Last Name: ‘.$user->getLastName().'<br />';

echo ‘Email: ‘.$user->getEmail().'<br />';

}

catch(Exception $e){

echo $e->getMessage();

exit();

}


?>


Definitely, the most important thing to note here is how an instance of the "User" class is called within the previous script. The following statement:

$user=new UserManager::CMS::User(‘Alejandro’,’Gervasio’,’alejandro@domain.com’);

creates a new $user object, where the name of the class is preceded by the corresponding namespace. Also, you should note the use of the (::) operator, which indicates that the class in question is linked to the "UserManager::CMS" namespace.

In this case, I used the "namespace" keyword to associate a sample class to a given namespace, which can be longer to code. There are a few additional methods in PHP 5 that permit you to perform the same task, but they’ll be properly reviewed in upcoming tutorials of the series.

For now, study the code samples developed previously to acquire a more solid background in using namespaces in PHP 5. And keep in mind that this feature will be available hopefully with the release of PHP 5.3.

Final thoughts

In this first part of the series, I provided you with a quick introduction to using namespaces in PHP 5. As you saw for yourself, using this feature is indeed a straightforward process that can be grasped with minor hassles.

In the next tutorial, I’m going to show you how to work with two classes that share the same name, but are linked to different namespaces. Now that you’re aware of the subject of this forthcoming article, you won’t want to miss it!

[gp-comments width="770" linklove="off" ]

chat sex hikayeleri Ensest hikaye