Tuesday, November 10, 2009

Using PHP Namespaces

PHP 5.3 introduces a much requested feature for object-oriented programmers: namespaces. At the time of this writing, version 5.3 of PHP was in development, but is planned on being released in the near future.

One of the purposes object-oriented programming is to remove ambiguous development and data access items. This basically means identifying common functionality and creating the most reusable framework possible, typically in the form of classes. When creating this functionality, you will begin to have issues with naming conventions and narrowing down functionality even further. To resolve this scoping issue, namespaces allow you to contain those bits of code even more.


It seems that PHP will be going with a similar namespace setup as C++. In order to declare a namespace, you will use the “namespace” keyword.

PHP
  1. namespace MyNamespace;
  2. class Test {
  3. public function hello() {
  4. echo ‘Hello’;
  5. }
  6. }
  7. ?>

The declaration above simply states that all elements contained in this script will be referenced with the “MyNamespace” namespace. You will need to place the “namespace” declaration at the top of the script.

In order to use a portion of functionality within this script, we will use the Scope Resolution Operator and instantiate the “Test” class.

  1. // Requiring the namespace file is a good indication that you don’t need to use namespaces, but this is only an example!
  2. require(‘the_file_above.php’);
  3. $test = new MyNamespace::Test();
  4. $test->hello();
  5. // Prints ‘hello’
  6. ?>