Namespaces in PHP

Written by Lucas, on Thu 06 December 2007, 14:22:38

One of the most requested features for PHP are namespaces, and they're finally coming. And we don't have to wait untill PHP6, because PHP 5.3 will have them already! And in this post we're going to take a look how namespaces in PHP look like.

Why namespaces are so important
When PHP5 was released, OOP became a lot more important in PHP applications. And with OOP comes classes. Sometimes, you want to use an existing framework, with an other lib. But when the framework and the lib have a class with the same name, you'll get an error.

A solution for this is to prefix your classnames, but in some cases, your classnames will get very long, and because we, programmers, are lazy, we don't want that.

And here's were namespaces come in, you can group classes under a name, and classes can have the same name, when both are in an other namespace.

So, you want to know how to use namespaces in PHP? Click the read more link.

First, we're going to define a namespace. This is done with the namespace keyword.

  1.  
  2. <?php
  3. namespace Framework::Database::MySQL;
  4.  
  5. class Connection
  6. {
  7.     protected $connection;
  8.    
  9.     public function __construct()
  10.     {
  11.         // Etc
  12.     }
  13. }
  14.  


This defines the class Connection in the namespace Framework::Database::MySQL. The namespace is of course not limited to one file, you can define the same namespace in other files too.

And here's how you call it:
  1.  
  2. <?php
  3. include_once 'classes/database/mysql.php';
  4.  
  5. $db = new Framework::Database::MySQL::Connection();
  6.  
  7. $db -> query("SELECT * FROM table");
  8.  


Well, such long namespace is pretty much to type, so in this case, it has no benefit from prefixing your classname. But namespaces have an extra feature: you can alias them.

  1.  
  2. <?php
  3. include_once 'classes/database/mysql.php';
  4.  
  5. use Framework::Database::MySQL as DB;
  6.  
  7. $db = new DB::Connection();
  8.  
  9. $db -> query("SELECT * FROM table");
  10.  


With the use keyword, you can alias a very deep namespace to a short name, which is easier to type. You can even alias a class in a namespace to a shorter name:

  1.  
  2. use Framework::Database::MySQL::Connection as MySQLConnection;
  3.  
  4. $db = new MySQLConnection();
  5.  


And remember: functions are in the namespace to ;)

PHP5.3 will probably be released in the first quarter of 2008, and if you want to know more about new features in PHP5.3, here are the results of a feature voting.

Tag Tags: oop php
Comments (2)