How do namespaces work in PHP?


Namespaces were implemented as of PHP 5.3.0 as a way to "encapsulate items".

I never really understood the real concept of it, and I always get confused with autoloading classes .

Could someone explain to me, in a simple way, how namespaces work, why they are used and if they have something with class autoload ?


namespace App\Http\Controllers; // usando namespace
use App\User;  // usando autoload


Namespaces are primarily useful to avoid name collision.

They were implemented in PHP 5.3.

It's very common to see older PHP libraries using a pattern that consists of using underline in class names, to avoid conflicts.

This was necessary because, as many libraries appeared, the names started to become "limited" because of the possibility of colliding names in common.

A great example is creating a class called Client . At least almost every library I've installed in a project has that name. That's where namespaces come in.

We can see an example of how this problem was solved in the past.

Example in old versions:


New versions:


In PHP 5.6 versions they become even more useful, as with the new use function , it has become easier to have a function repository as well.


 class WallaceMaxters\Helpers;

 function print_r($valor)
     echo '<pre>';
     echo '</pre>';

This function I created called print_r will not collide with print_r because of the namespace. But to use it in versions prior to php 5.6 , you would have to do something like:


Or yet:

 use WallaceMaxters\Helpers as h;


However, in PHP 5.6, as with classes, it is possible to create a local alias for that function.

use function WallaceMaxters\Helpers\print_r as pr



Class autoloading is an added feature so that classes are loaded ( include and require ) automatically as soon as they are instantiated.

So, instead of having to include a class every time you instantiate, you simply define a global rule for class loading.

An example of this is the PSR4 , which I love dearly .

Pattern that is widely used in libraries that can be installed by Composer ;


The default that most repositories use for their libraries, regarding the use of the namespace is:



namesace Laravel\Database;

class Eloquent {}
Scroll to Top