Namespaces in PHP

i’ve only just noticed that namespaces were introduced with php 5.3.0. I knew they were coming in php 6 but had no idea that they would be brought into the current trunk.

Namespaces will be extremely helpful for wordpress developers, some of whom seem to shie away from using classes to harbour plugin code. They will also be great for maintaining large code bases. Personally I use classes to create a local namespace. It’s an inappropriate use of object encapsulation but it works fine. Namespaces are definitely cleaner though.

So what are namespaces, for those not in the know? Put simply they enable users to re-use function and class declarations (and even in-built functions) without putting them in a class.
Normally this would cause php to barff

<?php 
function foo(){
  echo "hello world";
}
 
function foo(){
  echo "goodbye";
}

because foo() cannot be declared twice. It is not like a variable where the latter will overwrite the former.

With classes you can get around this problem

function foo(){
 echo "Hello World";
}
 
class bar{
 function foo(){
   echo "Hello World";
 }
 //and even
 function echo($text){
   echo $text;
  }
}

that is to say, classes/objects implicitly have their own namespace. you cannot directly address an object’s methods. Instead you have to tell php that it is the echo method of the bar object

bar::echo('sometext');
//or 
$bar = new bar();
$bar->echo('sometext');

namespaces provide a cleaner method of doing this. A sort of mini object that does not have formal methods and properties:

<?php
namespace samplecode
 
function echo($text){
  echo "<span style=\"color:red;\">$text</span>";
}
?>

and you can then address this function like so

samplecode::echo("hello world");

Some simple rules:

  • namespace declarations must be the first line of a physical file
  • namespaces must only contain constants, classes and functions. they cannot contain free code nor can they contain other namespaces (but you can stack namespaces with the :: operator)

There is quite a bit more to namespaces, particularly the ability to import them into the global scope, and the scope resolution hierarchy. As always the php manual is spectacularly helpful.

Leave a comment

Your comment