Namespace

Posted in PHP by

Namespaces are part of PHP since version "5.3". They allow you to structure your code similiar to c(#|++) and java. It works great together with autoloading, however there are some important issue you should know.

namespaces and useage It is important that namespace is the first piece of code in a php file, otherwise you will get a syntax error. You can have multiple namespaces in a file (feel free to put curly braces around them) by defining more of them. In order to use classes from other namenspaces or class that are not in a namespace (also called global namespace "\") one must use the proper namespace before the classname. Functions can be part of namespaces too. Take a look at this example, and read the comments.

<php
//No php code apart from comments before "namespace"
namespace Careout;
//this class can be accessed by using \Careout\Contact from other namespaces
class Contact{
...
private function mail($msg){
  $phpmailer = new \PHPmailer(); //the \ is required, because it is from the global namespace
...
}
}

the use keyword In c++ you often write "using namespace std;". PHP got a similar option. The code below explains it.

<php
namespace Gallery;
use \Careout\Contact;
use \Category as IsPartOf;
class Gallery{
...
public function doSomething(){
  $content = new Contact(); //because of the use keyword above.
  $category = new IsPartOf(); //use the as keyword to change the name.
}
}

Autoloading and issues Using the default autoloader "spl_autoload_register();" the namespaces will be resolved to folders. For example "\Careout\Contact" would include "Careout/Contact.php". This allows to structure your code a lot better. If you use the "use" keyword make sure that you do not "use Classname", because this throws an error. You still must have unique Classnames within the namespace scope.

Thats it for now. Questions? Feel free to ask.

Published at , Updated at 2011-10-25

next: Class prev: Debugging PHP with xdebug and notepad++