Using Aliases and the Autoload Function with Namespaces in PHP 5

Namespaces are an elegant approach to solving naming conflicts between the classes that are used by a PHP application. Indeed, it’s pretty common to suffer this problem during the development of a project that’s been charged to several programmers, and also when working with third-party libraries. This four-part series of articles, of which this is the last, shows you how to handle namespaces.


Hopefully, the introduction of PHP 5.3 will contribute to fixing these issues, since it will incorporate support for namespaces. In the meantime, as you wait for its  release, you may want to take a close look at this group of articles, which will walk you through the basics of using namespaces with PHP 5 by way of a hands-on approach.

And speaking of hands-on approaches, you’ll possibly recall that in the previous article of this series, I explained by means of distinct practical examples how to utilize the “use” PHP keyword to tie a couple of sample classes to different namespaces. Of course, one of the most important benefits in using this reserved word is that it requires a shorter syntax for declaring and utilizing a certain namespace. This approach appeals to many programmers.

It’s worth noting, though, that PHP 5.3 will let you use yet another notation that can be quite helpful when it comes to declaring namespaces in a more intuitive way. In this specific case, I’m talking about the ability to work with aliases, that is, meaningful words that can be directly linked to a given namespace.

If you’re interested in learning how to use aliases when working with namespaces, in this article I’ll be taking a close look at this topic, so you can learn quickly how to put this feature to work for you.

Now, it’s time to get rid of the preliminaries, and start discovering the real power in using namespace aliases with PHP 5. Let’s get going!

{mospagebreak title=Review: the use keyword}

I know that you want to see how to use namespace aliases with PHP 5, but first I’d like to reintroduce the example developed in the preceding article of this series. It was aimed at demonstrating how to utilize the “use” keyword to tie a sample “User” class to a fictional “UserManager::Blog” namespace.

That being said, here’s how the aforementioned example looked originally:

use UserManager::Blog::User;


class User{

private $firstName;

private $lastName;

private $email;

public function __construct($firstName,$lastName,$email){


throw new Exception(‘Invalid First Name parameter!’);



throw new Exception(‘Invalid Last Name parameter!’);



throw new Exception(‘Invalid Email parameter!’);






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




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

$user=new User(‘Alejandro’,’Gervasio’,’’);

// display user data

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

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

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

/* displays the following

First Name: Alejandro

Last Name: Gervasio




catch(Exception $e){

echo $e->getMessage();



As you can see by the above code sample, linking a class to a concrete namespace via the “use” keyword is indeed a no-brainer process that can be tackled with minor hassles. Naturally, the main advantage in using this reserved word in place of “namespace” is that it permits the use of a shortened syntax, but other than that, both of them have the same functionality.

At this point, you’ve hopefully recalled how to associate a basic “User” class to a specific namespace, which means that it’s time to start explaining how to use namespace aliases to accomplish the same task.

This useful topic will be discussed in depth in the section to come, so jump ahead and read the next few lines.

{mospagebreak title=Utilizing namespace aliases}

As I mentioned in the introduction, PHP 5.3 will also let you work with namespace aliases in a very simple fashion. Indeed, this process is reduced to associating  meaningful words with a certain namespace, which will require writing less, but more intuitive, code.

To demonstrate a typical use of namespace aliases, I’m going to create for you a fictional scenario. In this example, two validation classes that share the same name are associated with different namespaces. The first of these namespaces will be used in the context of a blog application, while the second one will be associated with a content management system.

So, based on this hypothetical situation, the use of namespace aliases could be exemplified in the following manner:

use DataSanitizer::Blog::Validator as BlogValidator;

use DataSanitizer::CMS::Validator as CMSValidator;


// create new instance of ‘BlogValidator’ class

$blogValidator=new BlogValidator();





// create new instance of ‘CMSValidator’ class

$cmsValidator=new CMSValidator();





catch(Exception $e){

echo $e->getMessage();



As you can see from the above example, two aliases, called “BlogValidator” and “CMSValidator” respectively, have been linked to a couple of namespaces, which should be easy for you to follow. These aliases are tied to the aforementioned validation classes, which logically share the same “Validator” name. Simpler to code and read, right?

In this particular situation, I created a pair of validation objects to check the validity of user-supplied data, such as the user’s full name, age and email address. In this way you can see clearly how the objects in question can be utilized independently.

So far, so good. Now that you hopefully grasped the logic that stands behind using namespace aliases, I think that it’s time to explore a few additional features regarding the use of namespaces with PHP 5, since there are a couple of useful things that I’d like you to learn.

As you’ll recall, all of the examples developed in the previous tutorials (and the current one, actually) used classes that were defined along with the scripts that utilized them. However, there’s an important point that deserves a deeper analysis here. What happens if you want to include these classes via the “__autoload()” PHP magic function, as you’ve probably done before?

Or, to put the question more plainly: how can a class that’s linked to a certain namespace be automatically included into a PHP script with “__autoload()”? Well, it’s a pretty simple process really, even when it requires using a slightly special syntax.

Therefore, in the last section of this tutorial, I’ll be explaining in detail how to work with namespaces and the “__autoload()” magic function. And additionally, you’ll see how to link a simple PHP function to a specific namespace.

As usual, to learn how all of these tasks will be accomplished, you’ll have to click on the link that appears below and read the next few lines.

{mospagebreak title=Autoloading classes and working with custom functions}

As I said in the previous section, the last two topics that I plan to discuss in this last part of this article are related to using namespaces with the “__autoload()” PHP magic function, and with regular functions as well.

First I’m going to show you a basic example of how to implement “__autoload()” when working with namespaced classes. Here’s a simple implementation for this magic function:

// implements the __autoload() with namespaced classes

function __autoload($className){



eval("class $className {}");

throw new Exception(‘Source class not found!’);


require_once $className.’.php’;


If you develop PHP applications that include source classes via the “__autoload()” function, then the above example should be pretty easy to understand. As you can see, I implemented this function in a fairly basic way, so it can include a class that’s been previously linked to a specific namespace.

The function, in this particular case, assumes that the class has been passed in the following form:


Thus, it first replaces the :: characters with a backslash, and then finishes its execution by attempting to load the class in question. Pretty simple to understand, right?

Now that I have quickly explained how to include a class that has been tied to a namespace, please take a look at this final example. It shows how to define and use two simple PHP functions, where the first one is linked to a sample “MyOffice” namespace:

namespace MyOffice

// define function within the ‘MyOffice’ namespace

function displayNameSpace(){

return ‘calling function from MyOffice namespace!’;


// define function in the global namespace

function displayNameSpace(){

return ‘calling function from the global namespace!’;


echo MyOffice::displayNameSpace();

// displays ‘calling function from MyOffice namespace!’

echo displayNameSpace();

// displays ‘calling function from the global namespace!’

Indeed, this last example is very simple to follow, trust me. As you can see, first a trivial “displayNameSpace()” function is linked to a “MyOffice” namespace, and then another function that has the same name is declared in the global namespace. Since these functions are actually different, they’ll also generate distinct outputs.

The following code snippet clearly demonstrates this process:

echo MyOffice::displayNameSpace();

// displays ‘calling function from MyOffice namespace!’

echo displayNameSpace();

// displays ‘calling function from the global namespace!’

With this last code sample, I’m finishing this introduction to using namespaces with PHP 5. Please keep in mind that all of the code samples shown in this group of tutorials will work (hopefully) with PHP 5.3, and not with earlier versions.

Final thoughts

Sad but true, this is the end of the series. I hope that all the material included in these articles will help you grasp more quickly how to utilize namespaces with PHP 5. Indeed, they can be quite useful for solving naming conflicts between classes and functions, something that might occur incidentally when the development of a PHP application is tackled by several programmers.

See you in the next PHP development tutorial!

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

chat sex hikayeleri Ensest hikaye