How do namespaces work in PHP?

Question:

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 ?

Example:

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

Answer:

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:

 Zend_Server_Client

New versions:

 Zend\Server\Client

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.

Example:

 class WallaceMaxters\Helpers;

 function print_r($valor)
 {
     echo '<pre>';
     \print_r($valor);
     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:

WallaceMaxters\Helpers\print_r($_POST);

Or yet:

 use WallaceMaxters\Helpers as h;

h\print_r($_POST);

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

pr($_POST);

autoload

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 ;

Standards

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

NomeDoFornecedor\NomeDaBiblioteca\NomeDaClasse

Example:

namesace Laravel\Database;

class Eloquent {}
Scroll to Top