Using Namespaces in PHP

Using Namespaces in PHP

Written by Dev Dojo on Jun 24th, 2016 Views Report Post

First let's start off by answering the question... "What the heck are these weird things called namespaces?" Well namespaces are basically a way of organizing your PHP classes and preventing from any kind of code conflicts. Let me give you a quick example of a class:


<?php 

namespace Dojo;

class Ninja
{

}

In the above example we are creating a new class called Ninja inside of the Dojo namespace. If we didn't use a namespace and we had another class with the name of 'Ninja' included our application we would get an error stating we cannot redeclare class. Luckily namespaces can solve this issue. So we could create another class like this:


<?php 

namespace Training;

class Ninja
{

}

Now, if we included both files in our application we can easily distinguish which Ninja class we want to use. As an example here's some code of how we would use the ninja classes:


<?php

// require both of our ninja classes
require "Dojo/Ninja.php";
require "Training/Ninja.php";

// create a new Ninja in the Dojo namespace
$ninja1 = new Dojo\Ninja();

// create a new Ninja in the Training namespace
$ninja2 = new Training\Ninja();

Both of these classes are different and probably have different functionality, so namespaces allows us to use the same class names and differentiating them by their namespaces. You can also use the PHP use function to make your code more readable. For instance, let's say that we want to just use Ninja instead of having to type Dojo\Ninja. we could do this:


<?php

// require both of our ninja classes
require "Dojo/Ninja.php";
require "Training/Ninja.php";

use Dojo\Ninja as Ninja;

$my_ninja = new Ninja();

We've just told our code that when I say Ninja I want to use Dojo\Ninja, this is great because then if we ever wanted to switch out the ninja we could simple change our use function to be:


use Training\Ninja as Ninja;

And that's it! Simple right?

One last thing I want to point out is that usually when using namespaces you will follow the folder structure of your namespaces so that way it's easier to find where these files are located. So our Training/Ninja.php file would probably live in a Training folder.

Here's a basic picture representation of how our Ninja Classes would look:

So, go ahead add those easy to remember and common class names in your projects. Just remember to give them a namespace :)

Comments (0)