Namespaces are mainly useful to avoid name collision.
Implemented in PHP 5.3.
It is very common to see older PHP libraries using a standard that consists of using underline
in class names, to avoid conflicts.
This was necessary because, as many libraries were emerging, the names began to become "limited" because there could be collisions of names in common.
A great example is to create 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 old days.
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 functionality of use function
, it has become easier to also have a repository of functions.
Example:
class WallaceMaxters\Helpers;
function print_r($valor)
{
echo '<pre>';
\print_r($valor);
echo '</pre>';
}
This function I created called print_r
will not have collision with print_r
on account of the namespace. But to use it in versions prior to php 5.6
, you’d have to do something like:
WallaceMaxters\Helpers\print_r($_POST);
Or else:
use WallaceMaxters\Helpers as h;
h\print_r($_POST);
But in PHP 5.6, like the classes, you can create a alias
location for that function.
use function WallaceMaxters\Helpers\print_r as pr
pr($_POST);
Autoload
Class autoload is a feature added for classes to load (include
and require
) automatically as soon as instantiated.
So instead of you having to include every time a class that will instantiate, you simply set a global rule for loading the class.
An example of this is the PSR4, whom I deeply love.
Standard that is widely used in libraries that can be installed by Composer;
Patterns
The standard that most repositories use for their libraries for using the namespace is :
NomeDoFornecedor\NomeDaBiblioteca\NomeDaClasse
Example:
namesace Laravel\Database;
class Eloquent {}
One of the answers in my question talks about him and has some examples including: http://answall.com/a/101738/20555, but I haven’t seen too much yet and your question will help me too. + 1
– Giancarlo Abel Giulian
Organize code, avoid function name conflict... avoid risk of collision. It is used to avoid conflicting definitions and introduce greater flexibility and organization into your code base. To use, the programmer needs to be very organized, because it is useless to use the resource without having solid knowledge in OOP.
– durtto