What are namespaces and use and when is it recommended to use them in an application?
What are namespaces and use and when is it recommended to use them in an application?
Namespaces are similar in many programming languages, as this answer explains How namespaces work in C #? (even the subject being a different languages)
I make the words of bigown mine:
It does not encapsulate anything
This understanding shows that despite the view that programmers have about the namespace being a module, a type box (as the first function indicates), it actually functions as a surname for the types. A surname functions as a way of naming a family. So you can have two Ricardos in the same environment without confusion, because one is Oliveira and the other is Silva.
Having understood what the utility is, let's understand how it works in PHP. In languages like Java, Actionscript and C # the namespaces are associated with the files "natively", in PHP this does not happen, you have to use require
or include
manually, ie I have to create something like this:
foo.php
<?php
namespace Foo\Bar;
class Baz
{
public function hello()
{
echo 'Olá mundo!';
}
}
index.php
<?php
use Foo\Bar\Baz;
require 'foo.php';
$test = new Baz;
The use
does nothing, even with spl
, in PHP it only serves to create nicknames, for example suppose you have two classes that the name is the same, if you do this:
<?php
use Aa\Bb\MinhaClasse;
use Xx\Yy\MinhaClasse;
At the time of using MinhaClasse
it would conflict, so you can use it like this:
<?php
use Aa\Bb\MinhaClasse;
use Xx\Yy\MinhaClasse as MinhaClass2;
$a = new MinhaClasse;
$b = new MinhaClasse2;
I mean at the moment you use this:
<?php
use Foo\Bar\Baz;
$test = new Baz;
You're just creating a "fast nickname."
You can also use directly:
<?php
$a = new \Aa\Bb\MinhaClasse;
$b = new \Xx\Yy\MinhaClasse;
Note that within namespaces you can add others like functions and believe that until you run some things, example functions:
<?php
namespace Foo\Bar;
function file($path) { ... }
In this way it will not conflict with the native php function called file
:
file('oi.txt');
\Foo\Bar\file('oi.txt');
Enjoy and read about the native functions and namespaces here:
Is "\" required at the beginning of native functions when using namespace?
SPL is a set of native PHP functions and classes that were created to solve a number of situations, such as PHP does not load natively, but it is possible to use spl_autload
, as I explained here What is spl_autoloader_register in PHP? , in this way the files will be associated by dividing folders into namespaces, similarly to C #, Java and Actionscript3.
According to the official namespaces PHP documentation , it is basically a way to encapsulate items .
In practice, it serves to better organize your code by grouping classes and avoiding name conflicts, such as third-party classes.
You can use it to separate modules, groups of classes, or in the way you think will best organize and encapsulate your code.