PHP 5.3 and namespaces

Introduction

It's a feature of many high-level languages today: namespaces. Modern languages like Java or C# had them built in from the beginning. PHP was missing this feature for a long time, but finally the developers decided to build them into php 5.3. In this article I'd like to show how to use namespaces in php and what they are good for.

First Script

The next few lines will show you the basics on namespaces in php:

database.namespace.php <?php namespace database; abstract class db { protected $sql; protected $query_count; public function getQueryString() { return $this->sql; } abstract protected query(); public function setQuery($sql) { $this->sql = $sql; } } public class mySQL extends db { // Implementing all abstract methods from db here } ?>

There are only two new keywords introduced for the namespacing ability of PHP. The first one is 'namespace', which specifies the name of the namespace for the rest of the file. The second one appears in the next script:

main.php <?php // Including the namespace require_once('database.namespace.php'); // Importing the mySQL class into the current namespace use database::mySQL; // Creating an instance of the mySQL class. $dbconnection = new mySQL(); // We can now use the object.. $dbconnection->setQuery("SELECT id FROM table"); ?> The 'use' keyword is used to import complete namespaces or in this case a specific class of our namespace.

Namespaced projects

Now what is all this good for? Well, imagine a huge community project where you need to merge a board and a news system. Both come with a class named 'User'. The old way it would have been necessary to rename the classes to 'BoardUser' and 'NewsUser' to prevent collisions. Now we can just pull them into two different namespaces and import them when needed.

<?php namespace Community::Board; class User { public const NAME = 'Hal9000'; } ?> <?php namespace Community::News; class User { public const NAME = 'Hagbard'; } ?> <?php use Community::Board; echo Board::User::NAME; use Community::News::User as NewsUser; echo NewsUser::Name; ?> This example shows two different ways of importing a namespace. The first one ist includes all classes inside the Community::Board namespace, while the second one directly imports the the User class inside the Community::News namespace and renames it to NewsUser for further usage.

Recommended books on this topic

Pro PHP: Patterns, Frameworks, Testing and More Pro PHP: Patterns, Frameworks, Testing and More by Kevin McArthur

Comments (0) |

No comments yet!

Submit Comment