Working With Different Namespaces in PHP 5

Namespaces have been available for a long time in mature object-oriented languages like Java and C++. However, there’s good news on the horizon, since they will also be available in PHP 5.3 (hopefully). That’s a good reason to start learning how to use them within the context of object-oriented PHP applications. This is the second part of a four-part series that shows you how.

In this group of articles you’ll find an approachable guide to utilizing namespaces with PHP 5 classes. In addition to learning the theoretical concepts that surround this topic, you’ll be provided with numerous code samples to help you understand quickly how to use them in different cases.

And now that I introduced you to the main subject of this series of articles, it’s an excellent time to recapitulate very quickly the topics that I covered in the preceding tutorial. As you’ll surely recall, I left off that article discussing how to tie a given PHP 5 class to a specific namespace by means of the “namespace” keyword.

In that particular situation, I defined a sample “User” class, which was linked to a fictional “UserManagement::CMS” namespace via the aforementioned keyword, assuming that the class in question would be utilized in the context of a user-related content management system.

Of course, although this hands-on example was actually pretty basic and had a rather limited functionality, it was useful enough to demonstrate how to associate a determined PHP 5 class to a concrete namespace.

However, so far I’ve shown you how to work only with one class, tied to a specific namespace. Thus, in this second part of the series I will illustrate how to link two classes that share the same name to different namespaces. Doing so will show you more clearly the actual functionality of using distinct namespaces in the context of an object-oriented PHP application.

So, are you ready to continue learning more useful things about working with namespaces in PHP 5? Then let’s jump in!

{mospagebreak title=Linking a single class to a specified namespace}

Before I explain how to associate two classes that share the same name to different namespaces, it’d be a good idea to review the practical example built in the previous article of the series. It demonstrated how to perform this process with only one class.

Basically, the code sample corresponding to the aforementioned example looked like this:


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();

}


As you can see, the above example shows a typical case where a single class has been tied to a concrete namespace. Speaking more concretely, in this case the previous “User” class has been linked to a “UserManagement::CMS” namespace by means of the pertinent “namespace” keyword.

Finally, an instance of this class is created by using the following expression:


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


That’s pretty simple to understand, right? The actual functionality of using namespaces, however, is revealed when two or more classes that share the same name are included in one single PHP application. It’s probable that at this moment you’ll be wondering how this can be achieved without getting an error from the PHP interpreter.

As you may guess, it’s possible to associate each of these classes with a different namespace, in this way solving any naming conflicts in an elegant manner.

In the following section, I’m going to explain in detail how to perform this task. To learn how this will be done, please click on the link that appears below and read the next few lines.

{mospagebreak title=Linking two classes to different namespaces}

As I mentioned in the section that you just read, it’s possible to link two classes that have been named the same to different namespaces, something that can be very useful in those cases where you’re working with third-party software.

In order to illustrate this concept, I’m going to create one sample file called “usercms.php,” which will include the “User” class that you saw before, along with the definition of the namespace where it will be used.

Having said that, here’s how this first sample file looks:


(definition for ‘cmsuser.php’ file)


<?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;

}

}

?>


So far there is nothing unexpected, right? As you can see, the previous “usercms.php” file first declares a “UserManager::CMS” namespace, and then  includes the signature of the pertinent “User” class.

Now that I already tied the previous “User” class to the “UserManager::CMS” namespace, I’m going to define a similar class. As you’ll see in a moment, this class will be linked to a different namespace. Of course, all of this code will be encapsulated into another sample file, called “bloguser.php,” whose definition is listed below:


(definition for ‘bloguser.php’ file)

 

<?php


namespace UserManager::Blog;

 

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;

}

// get all user data

public function getAll(){

return ‘First Name: ‘.$this->firstName.’ Last Name: ‘.$this->lastName.’ Email: ‘.$this->email;

}

}

?>


Certainly, things are getting really interesting now! As you can see, I built a second “User” class that extends the functionality of the first one. However, I’ve done this only for example purposes, since the most important detail to stress here is that both classes have been linked to different namespaces.

At this point, are you beginning to realize how useful namespaces can be when working with a group of classes that have the same name? I hope you are, because this is precisely the most relevant advantage in using namespaces in the context of an object-oriented application.

So far, so good. At this stage, you have hopefully learned, by means of the two previous sample files, how to tie two “User” classes to distinct namespaces. Thus, the next step will be aimed at demonstrating how the classes in question can be called independently within the same PHP script, even when they share the same name.

To see how this brand new script will be developed, please click on the link that appears below and read the following section. I’ll be there, waiting for you.

{mospagebreak title=Working with objects that belong to different namespaces}

Since in the previous section you learned how to link two sample classes named “User” to distinct namespaces, it’s time to see how to use their instances within the same PHP script, without getting any errors from the PHP engine.

That being explained, please take a look at the following code sample, which demonstrates how to display information about a couple of fictional users by utilizing the two namespaces declared earlier. Here it is:


// include class files

require_once ‘bloguser.php’;

require_once ‘cmsuser.php’;


try{

// create new instance of ‘User’ class (belongs to UserManagement::CMS namespace)


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

// display user data

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

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

echo ‘Email: ‘.$cmsUser->getEmail().’<br />’;

 

/* displays the following


First Name: Alejandro

Last Name: Gervasio

Email: alejandro@domain.com

*/


// create new instance of ‘User’ class (belongs to UserManagement::Blog namespace)


$blogUser=new UserManager::Blog::User(‘John’,'Doe’,'john@domain.com’);

// display user data

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

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

echo ‘Email: ‘.$blogUser->getEmail().’<br />’;


/* displays the following


First Name: John

Last Name: Doe

Email: john@domain.com

*/

}

catch(Exception $e){

echo $e->getMessage();

exit();

} 


As you can see from the earlier example, I first created a pair of users for each “User” class, and then displayed some basic data about them on screen. Logically, the most interesting aspect to note here is how each of these classes are instantiated by means of their corresponding namespaces. Even when there are actually two classes named “User,” they belong to distinct namespaces. Pretty good, right?

And with this last example, I have finished this humble introduction to linking two sample classes to different namespaces. As usual, feel free to use all of the code samples developed in this article, so you can extend your existing skills for using namespaces with PHP 5.

Final thoughts

In this second episode of the series, you hopefully learned how to tie a couple of basic sample classes that have the same name to different namespaces. As you saw before, this process is pretty intuitive, so you shouldn’t have major problems understanding how it works.

In the upcoming article, I’m going to show you how to employ the “use” PHP keyword to declare several namespaces within the same application. Therefore, now that you’re aware of the topics that will be discussed in the next tutorial, you can’t miss it!

[gp-comments width="770" linklove="off" ]
antalya escort bayan antalya escort bayan