Namespaces are mostly useful for avoiding name collision.
They were implemented in PHP 5.3.
It is very common to see older PHP libraries using a pattern that uses underline
in the class name to avoid conflicts.
This was necessary because, as many libraries were being developed, names began to be "limited" because of collisions of common names.
A great example is to create a class called Client
. At least most libraries I've installed on a project have this name. That's where the namespaces come in.
We can see an example of how to solve this problem once.
Example in older versions:
Zend_Server_Client
New versions:
Zend\Server\Client
In versions of PHP 5.6 they become even more useful, since with the new feature of use function
, it has become easier to also have a function repository.
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:
use WallaceMaxters\Helpers as h;
h\print_r($_POST);
But in PHP 5.6, just like the classes, you can create a% local_local for that function.
use function WallaceMaxters\Helpers\print_r as pr
pr($_POST);
Autoload
Class autoload is a feature added so classes are loaded automatically ( alias
and include
) automatically as soon as instantiated.
So, instead of having to include a class to instantiate every time, you simply set a global rule for loading the class.
An example of this is the PSR4 , which I deeply love.
Pattern that is widely used in libraries that can be installed by Composer ;
Standards
The standard that most repositories use for their libraries, regarding the use of the namespace is:
NomeDoFornecedor\NomeDaBiblioteca\NomeDaClasse
Example:
namesace Laravel\Database;
class Eloquent {}