Tag: namespaces

Mastering Namespaces in PHP at PHPBenelux Conference

On Saturday 29th January I held my Mastering Namespaces in PHP presentation at the PHPBenelux Conference. The second edition of this awesome conference has put the conference on the European map as a classic must-go-to. The ratings are through the roof!

See what attendees are saying:

  • “already the best conference of the year”
  • “Great conference! The best i had in years.”
  • “5 THUMBS UP!!”
  • “Top class speakers, which make a good schedule”

I must say I am really happy I was part of making all those people have a wonderful day by giving the Mastering Namespaces in PHP Presentation which was – although for some people lacking some colour in the black and white slides – regarded very good:

  • “Spot on. All aspects of namespaces were covered, and explained well. Included with examples & references”
  • “The subject was well covered, and Nick clearly knew what he was talking about.”
  • “Good presentation about namespaces! Good explanation about how it works, some pitfalls and best practices. I liked it a lot!”
  • “Clear introduction into Namespacing in PHP with the good and bad clearly outlined. Very informative and thorough.”

To all the people who attended and took the time to rate my presentation at joind.in a big thanks,

See you next time
Nick Belhomme

Attend my presentation at the PHPBenelux 2011 conference

Hi ladies and gents,
I am happy to announce I will be speaking at PHPBenelux Conference 2011.
That means you will learn something about namespaces in PHP. If you never worked with them before or aren’t feeling very confident using them, attend this presentation. Namespaces are a crucial tool that should be found in every PHP developers toolkit (don’t be a dinosaur and in a couple of years a fossil).

If namespaces is not enough for you to attend this awesome conference, maybe the other speakers do the trick. Amongst several others are Rob Allen the main author of Zend Framework in Action and a contributor to the Zend Framework. He is also a member of the Zend Framework Education Advisory Board and will be giving a talk that will introduce Zend Framework 2 and look why it has been created and what’s different compared to ZF1.
Derick Rethans most famous for creating Xdebug, a tool every PHP developer uses on a daily basis (you practice Stepping and do unit tests right?). He is also the author of several books and will bring his geolocation know-how to the scene.
Elizabeth Naramore co-author of several PHP books and community development manager at Geeknet which includes sites such as SourceForge, Slashdot, Geek.com, ThinkGeek. She will jump start the conference as a keynote speaker.

Still not convinced? Check the many high profile speakers who will be attending.

You should register your seat now, and look forward to ride a highway of information, plunge into networking (the social bowling event will help with that!! Whaaat there is a bowling alley? Yes there is!) and generally have a blast of fun!


See you at the PHPBenelux conference – January 28 & 29, 2011, Antwerp, Belgium

yours truly,
Nick Belhomme

update 2010-11-22: The Schedule is available

PHP 5.3.3 Namespaces

Purpose of the entry

With PHP5.3.3 recently released I really feel it is time that php developers are taking namespaces seriously. If you don’t I guarantee you will be out of a job within five years. Namespaces are a fundamental part of the future of PHP.
The big frameworks like Symfony and Zend Framework have understood this and build their latest versions (2.0) with namespace support.
You all have namespaced before using the filesystem and long class names. This is still a valid way to go, but as time evolves you will see this less and less. Probably the filesystem structure will remain but not the long tedious names. We will start to use aliasing or namespace scopes for that.


  • Getting started with namespaces
  • resources

Getting started with namespaces

So how does one begin with namespaces? Well simply by doing it. And what better way do to it than by example.
In this blog post I will explain how to use namespaces in a project and how to import two external libraries into it.
One your own and the other a real third party.

It is a small project and solely for demonstration purposes, kept intentionally very small but explanatory by nature.
So do not heckle me for design decisions and such, those would only cloud the goal of this small presentation.

You can download a working copy of the project so you can play with it and experience namespaces first hand.

I will wait a minute or so.

Done and loaded in the browser? Great, let’s get on with it.

As you see I first put all code outside of my public folder (httpdocs). I have put everything regarding setting include_paths
and constants in Application.php.

// Application.php
namespace {
    ini_set('display_errors', true);

    function __autoload($class) {
        $class = str_replace('\\', '/', $class);
        $class = preg_replace('/^Application/', 'application', $class);
        require_once $class.'.php';


namespace Application {
    const PROJECT_PATH = '../';

    $bootstrap = new Bootstrap(new \Nick\PlayBowl());

The file itself contains procedural code with two namespaces. You can attach as many namespaces as you want inside a file by encapsulating them between brackets. The namespace operator must be the first thing defined in a file.
In Application.php we have a global namespace in which we will register the autoload and setup the include_path. Autoloading namespaces
has to be done in the global scope. It also makes sense to set the include path in the global scope. Everything related to our application
itself goes into the Application namespace.

We will load the Bootstrap class from the namespace Application. Class names that do not contain a backslash like Bootstrap can be resolved in 2 different ways. If there is an import statement that aliases another Bootstrap to Bootsrap, then the import alias is applied.
Otherwise, the current namespace name is prepended to Bootsrap. Because we did not use the use operator no aliasing or importing is done, and Bootstrap will resolve to Application\Bootstrap().
Because no leading backslash is used when we defined the “namespace Application” we have specified an unqualified name. PHP will resolve this by adding the namespace to the current used namespace. In this case it is the \ (global) namespace.

// Bootstrap.php
namespace Application;
class Bootstrap
    protected $_game;

    public function __construct(\Nick\PlayBowl $game)
        $this->_game = $game;

    public function _setupSomeUglyNamedNameSpace()

    public function run()

Inside the Bootstrap.php file we have used the namespace operator to register the class Bootstrap under the Application namespace. We
did this by opening Application as the current namespace and then adding constants, functions and or classes to it. In our example the class Bootstrap.
Making it available by calling it from outside the current namespace using \Application\Bootstrap(); Just as we did with \Nick\PlayBowl in Application.php. As you can see we can also force the type in the constructor using namespaces just as we did with long class names.

In \Application\Bootstrap we use already 3 namespaces: Application, Nick and SomeUglyNamedNameSpace to target specific functions, constants and classes.

we have two different use cases for the namespace operator. Outside a namespace we switch the scope to a new namespace using namespace nameOfScope and inside a namespaced scope we can use the operator to target the current scope. This making the namespace operator the equivalent of the class self:: operator.

We have registered an instance of \Nick\Playbowl to $this->_game and we call its methods in the run() method. Let us take a look at that.
Because here you will see aliasing.

namespace Nick;
use \SomeUglyNamedNameSpace as Lib;
class PlayBowl
    public function aim()
        echo 'you are aiming at the pins<br />';

    public function roll()
        echo 'you release the ball and wait in anticipation<br />';

    public function getHits()


    protected function _hit()
        $calculator = new Calculator();
        if ($calculator->isGood()) {
            echo 'you hit all pins<br />';

    protected function _hit2()
        $calculator = new namespace\Calculator();
        if ($calculator->isGood()) {
            echo 'you hit all pins<br />';

    protected function _getPinsHit()
        $someCalculator = \SomeUglyNamedNameSpace\Calculator::factory(\SomeUglyNamedNameSpace\Calculator::SCIENTIFIC);
        $num = $someCalculator->add(2, rand(2,4));
        echo sprintf('%d pins hit', $num),'<br />';

    protected function _getPinsHit2()
        $someCalculator = Lib\Calculator::factory(Lib\Calculator::SCIENTIFIC);
        $num = $someCalculator->add(2, rand(2,4));
        echo sprintf('%d pins hit', $num),'<br />';

    protected function _getPinsHit3()
        $someCalculator = new Lib\Math\Addition\Scientific();
        $num = $someCalculator->add(2, rand(2,4));
        echo sprintf('%d pins hit', $num), '<br />';

    protected function _getPinsUnexisting()
        try {
            $someCalculator = Lib\Calculator::factory('science');
        } catch (Lib\Exception $e) {


Ok a lot is going on in here. Or so it seems… What I actually have done is included a lot of duplicate code for your pleasure.
let us first take a look at hit() and hit2(). Those two are identical. My preference is the hit() method. I will explain.
This method is identical to hit2, but this function doesn’t use the namespace operator, because by default PHP will prepend it with the current namespace. In hit two we explicitely use the namespace operator and so we manually prepend the current namespace to the classname. In hit2 the namespace operator is the namespace equivalent of the self operator for classes.

Time to take a look at the _getPinsHit methods. Again these are example methods. Were in _getPinsHit we use the third party library SomeUglyNamedNameSpace and use the fully qualified namespace (leading backslash in the namespace).

_getPinsHit2() does exactly the same thing but here we use the namespace aliasing functionality. We have at the top of the file defined the
namespace alias with the use of the use operator. use \SomeUglyNamedNameSpace as Lib; Thereby effectively shortening that uglynamespace or preventing namespace clashes.

_getPinsHit3() goes further into that example by showing that you can easily use that aliased name as the base for nested namespaces.
Note that you can not have real nested namespaces like you can have nested ifs. You can only have nested namespaces like you can have nested classnames. Thus by appending the namespace names, extending the scope. Like in this example. The class Scientific is a part of the namespace Lib\Math\Addition\ which in his turn is a part of \Lib\Math\ and so on…

_getPinsUnexisting Doesn’t really demonstrate something in this class but I needed to show you the difference between global namespace functions and other namespaced functions.

But first let us take a look at the other usage of the use operator. The import usage. This will be used a lot to shorten names.

namespace SomeUglyNamedNameSpace;
use SomeUglyNamedNameSpace\Math\Addition;
class Calculator
    const SCIENTIFIC = 'scientific';

    static public function factory($type = 'scientific')
        if (self::SCIENTIFIC === $type) {
           return new Addition\Scientific();
        throw new Exception('you must specify a valid Calculator type');

We used to do “return new SomeUglyNamedNameSpace_Math_Addition_Scientific();” , now with namespaces we can finally shorten it with:
use SomeUglyNamedNameSpace\Math\Addition; and from then of on you can call in the current scope simply “return new Addition\Scientific();” Which makes your code much easier to read.

Ok of to our final piece of example code:

namespace SomeUglyNamedNameSpace;
class Exception extends \Exception
    static protected $_logFile;

    public function log()
       file_put_contents(self::$_logFile, 'this will call the namespaced function');
       \file_put_contents(self::$_logFile, date('H:i:s')."\t".'this will call the global function, which we all know');

    static public function setLogFile($path)
        self::$_logFile = $path;

function file_put_contents($filename, $string) {
    echo 'this is '.__NAMESPACE__.' function';

I know in good design the last function should not have been in that same file, but this example if for the understanding of namespaces and nothing else. It isn’t a real Bowling game either 😉

Ok what is going on?

We first Extend the global Exception class which we all use everyday and implemented a log() method.
This log method does two things. It first calls the file_put_contents as an unqualified namespace (no backslash operator in the name found).
As before this will have the effect that it will first try to prepend the current namespace to the function and thus will find the function at the bottom of the file. And secondly we call explicitily the good file_put_contents, the global scope version! Which will nicely log the error message to the log file setted in our Bootstrap.php

I hope this small presentation on namespaces made a lot of things clear.


See you soon,

Nick Belhomme

Opening keynote by Andrei Zmievski at DPC09 – The evolution of PHP

Purpose of the entry

On Friday June 12th 2009 the Dutch PHP Conference started with a small introduction by Cal Evans, director of PCE at Ibuildings and previous editor-in-Chief of DevZone at Zend, Inc.
Cal welcomed us all at the third edition of what will become one of the major players concerning php conferences in Europe. The conference itself is packed with great talks on various subjects regarding programming. From the novice topics like the excellent talk from Ben Ramsey on “Grokking the REST Architecture” to the more advanced like “Trees in the Database: Advanced Data Structures” by Lorenzo Alberton. The latter I could unfortunately not attend, a man has got to make choices. I was attending Ben Ramsey’s second talk on REST because the first one was really really interesting. I did not have to choose which opening keynote to attend. There is only one per day and the first day was opened by Andrei Zmievski. He is a real entertainer. He brought the evolution of PHP, the new features in PHP 5.3 and PHP 6.0. He also said what PHP 7.0 will not be.
In this entry I will give an overview on the talk given by the main guy responsible for the official PHP releases.


  1. What is PHP
  2. PHP is mature and version 5.3 will arrive shortly
  3. PHP 6.0 is coming and with it Unicode and traits
  4. PHP7.0
  5. Resources
  6. Closing notes

What is PHP

PHP or Hypertext PreProcessor is a dirty language with a very low learning curve. This has been the success of the dominating web language. It is dirty because it was build upon release upon release. Never able to clean up some errors made in the beginning when the language was starting to evolve. This resulted in some function parameter inconsistencies and design issues that could have been done a different way. Because PHP took features from other languages it is a mix of various things. PHP is a ball of nails, it is not a full breed, but more like a mutt. But you got to love the mutt. It works brilliantly and does what it needs to do. And with every release it becomes more and more mature, more and more beautiful. Mutts often are stronger than full breeds also…

PHP is mature and version 5.3 will arrive shortly

Within a couple of weeks the long awaited PHP 5.3 version will be released as stable.
Like PHP 5.1 made a huge leap with the PDO integration so will 5.3 with namespaces. Andrei made some jokes about the decision to use backslashes as the namespace symbol. He did this with mails send to the mailing list and I must say it was hilarious. The message he wants to give to the community is: Yes we have used the \, stop whining about it and start adopting it. You have no choice. Decisions have to be made and we, the PHP Core developers have made ours. Personally I am sure namespaces will change the way programmers and framework architects develop their applications. Maybe not immediately but over the years they will.
Things like lambda functions and closures are also supported and I am positive people will start to adopt to this new functionality right away. I know I will.
As I said before PHP is a mutt and it has adopted a lot of features from other languages. Java is one of them. The tradition is continuous and with the introduction of phar files I am positive a lot of deployment will change. Phar allows you to pack your entire project into a single file, pretty much like a tar or zip file. You can browse and include these files from the Phar file from within your code as if it was a normal directory on your filesystem. You can also execute your application from within the file entirely. As you can imagine this gives big benefits on deployment where some files always have to be uploaded as a single pack to ensure the sequential uploading of files to avoid the resulting breaking of the application for a period of time. Or the way libraries and common applications like phpMyAdmin are distributed.
If you want to know more about lambda, closures, phars and namespaces there are some great resources available and I will give you a list at the end of this article.

PHP 6.0 is coming and with it Unicode and traits

Traits is PHP solution on the multiple inheritance problem. There is no diamond issue here and still you can use the functionallity of multiple classes from within a class. You will still be limited to inheritance from a single parent, and this is a good thing, but you can import (dynamically copy/paste) methods from a secondary or n+ other classes. Unicode will solve the internationalization problems, problems with some string functions and even allow chinese programmers to program in chinese. Do not expect Andrei or me for that same matter to debug such applications. 🙂


PHP7.0 is coming and it will offer lots more of functionality and great stuff. What it will be nobody knows (maybe some do?), but what is known is that it will not be PHP designed from scratch. A version polished to perfection. The ultimate clean language. Such a language does not exist and if someone is eager to build it, it will not be called PHP. PHP is a powerful tool. If used in experienced hands you can develop applications with it that will astound everybody. Go and use PHP. And if you are using PHP love it, cherisch it and welcome the changes.


Closing notes

Andrei Zmievski is a wonderful speaker with lots of charisma. With his opening keynote he awoke my interest of using all the new functionalities future releases of PHP will offer. As a core PHP developer and leader of the PHP-GTK project he was not afraid to make various jokes on himself, the community and PHP. Which made the talk very lighthearted and easy to digest. One of the cool stuff was when he pointed to an ini setting called y2k_compliance in PHP3 which did nothing but made you feel safe. Like a placebo for PHP. That was so much fun!
His talk made me keen on using all the new PHP 5.3 features and made me look forward to using PHP 6.0. And with me a lot of other developers were feeling good at heart and ready to attend all the talks the dutch PHP conference had to offer. The stage was set to be one of the best content wise conferences I ever attended.

Happy coding from sunny Belgium,
Nick Belhomme