Introduction aux espaces de noms

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

Que sont les espaces de noms ? Dans leur définition la plus large, ils représentent un moyen d'encapsuler des éléments. Cela peut être conçu comme un concept abstrait, pour plusieurs raisons. Par exemple, dans un système de fichiers, les dossiers représentent un groupe de fichiers associés et servent d'espace de noms pour les fichiers qu'ils contiennent. Un exemple concret est que le fichier foo.txt peut exister dans les deux dossiers /home/greg et /home/other, mais que les deux copies de foo.txt ne peuvent pas co-exister dans le même dossier. De plus, pour accéder au fichier foo.txt depuis l'extérieur du dossier /home/greg, il faut préciser le nom du dossier en utilisant un séparateur de dossier, tel que /home/greg/foo.txt. Le même principe s'applique aux espaces de noms dans le monde de la programmation.

Dans le monde PHP, les espaces de noms sont conçus pour résoudre deux problèmes que rencontrent les auteurs de bibliothèques et d'applications lors de la réutilisation d'éléments tels que des classes ou des bibliothèques de fonctions :

  1. Collisions de noms entre le code que vous créez, les classes, fonctions ou constantes internes de PHP, ou celle de bibliothèques tierces.
  2. La capacité de faire des alias ou de raccourcir des Noms_Extremement_Long pour aider à la résolution du premier problème, et améliorer la lisibilité du code.

Les espaces de noms PHP fournissent un moyen pour regrouper des classes, interfaces, fonctions ou constantes. Voici un exemple de syntaxe des espaces de noms PHP :

Exemple #1 Exemple de syntaxe des espaces de noms

<?php
namespace mon\nom; // Voyez la section "Définition des espaces de noms"

class MaClasse {}
function
mafonction() {}
const
MACONSTANTE = 1;

$a = new MaClasse;
$c = new \mon\nom\MaClasse; // Voyez la section "Espace global"

$a = strlen('bonjour'); // Voyez "Utilisation des espaces de noms : retour
// à l'espace global

$d = namespace\MACONSTANTE; // Voyez "L'opérateur namespace et la constante __NAMESPACE__

$d = __NAMESPACE__ . '\MACONSTANTE';
echo
constant($d); // Voyez "Espaces de noms et fonctionnalités dynamiques"
?>

Note: Les noms d'espaces de noms ne sont pas sensible à la casse.

Note:

Les espaces de noms PHP, mais aussi les noms composés commençant par ces noms (comme PHP\Classes) sont réservés pour l'utilisation interne du langage, et ne doivent pas être utilisés dans le code de l'espace utilisateur.

add a note add a note

User Contributed Notes 6 notes

up
782
SteveWa
13 years ago
Thought this might help other newbies like me...

Name collisions means:
you create a function named db_connect, and somebody elses code that you use in your file (i.e. an include) has the same function with the same name.

To get around that problem, you rename your function SteveWa_db_connect  which makes your code longer and harder to read.

Now you can use namespaces to keep your function name separate from anyone else's function name, and you won't have to make extra_long_named functions to get around the name collision problem.

So a namespace is like a pointer to a file path where you can find the source of the function you are working with
up
262
Dmitry Snytkine
12 years ago
Just a note: namespace (even nested or sub-namespace) cannot be just a number, it must start with a letter.
For example, lets say you want to use namespace for versioning of your packages or versioning of your API:

namespace Mynamespace\1;  // Illegal
Instead use this:
namespace Mynamespace\v1; // OK
up
138
pierstoval at gmail dot com
9 years ago
To people coming here by searching about namespaces, know that a consortium has studied about best practices in PHP, in order to allow developers to have common coding standards.

These best practices are called "PHP Standard Recommendations" , also known as PSR.

They are visible on this link : http://www.php-fig.org/psr

Actually there are 5 coding standards categories :
PSR-0 : Autoloading Standard , which goal is to make the use of Namespaces easier, in order to convert a namespace into a file path.
PSR-1 : Basic Coding Standard , basically, standards :)
PSR-2 : Coding Style Guide, where to put braces, how to write a class, etc.
PSR-3 : Logger Interface , how to write a standard logger
PSR-4 : Improved Autoloading , to resolve more Namespaces into paths.

The ones I want to point are PSR-0 and PSR-4 : they use namespaces to resolve a FQCN (Fully qualified class name = full namespace + class name) into a file path.
Basic example, you have this directory structure :
./src/Pierstoval/Tools/MyTool.php

The namespacing PSR-0 or PSR-4 standard tells that you can transform this path into a FQCN.
Read the principles of autoload if you need to know what it means, because it's almost mandatory ;) .

Structure :
{path}/autoloader.php
{path}/index.php
{path}/src/Pierstoval/Tools/MyTool.php

Files :

<?php
   
// {path}/index.php
   
include 'autoloader.php';
   
$tool = new Pierstoval/Tools/MyTool();
?>

<?php
   
// {path}/src/Pierstoval/Tools/MyTool.php
   
namespace Pierstoval\Tools;
    class
MyTool {}
?>

<?php
   
// {path}/autoloader.php
   
function loadClass($className) {
       
$fileName = '';
       
$namespace = '';

       
// Sets the include path as the "src" directory
       
$includePath = dirname(__FILE__).DIRECTORY_SEPARATOR.'src';

        if (
false !== ($lastNsPos = strripos($className, '\\'))) {
           
$namespace = substr($className, 0, $lastNsPos);
           
$className = substr($className, $lastNsPos + 1);
           
$fileName = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
        }
       
$fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';
       
$fullFileName = $includePath . DIRECTORY_SEPARATOR . $fileName;
       
        if (
file_exists($fullFileName)) {
            require
$fullFileName;
        } else {
            echo
'Class "'.$className.'" does not exist.';
        }
    }
   
spl_autoload_register('loadClass'); // Registers the autoloader
?>

A standardized autoloader will get the class you want to instanciate (MyTool) and get the FQCN, transform it into a file path, and check if the file exists. If it does, it will <?php include(); ?> it, and if you wrote your class correctly, the class will be available within its correct namespace.
Then, if you have the following code :
<?php $tool = new Pierstoval/Tools/MyTool(); ?>
The autoloader will transform the FQCN into this path :
{path}/src/Pierstoval/Tools/MyTool.php

This might be the best practices ever in PHP framework developments, such as Symfony or others.
up
2
shewa12kpi at gmail dot com
2 years ago
<?php
//Here is the simple use case of namespace. See how we can use same named class with the help of namespace. This is how namespace resolve naming collision.

namespace Mobile;

class
User
{

    public
$name = 'mobile user';
}

$user = new \Mobile\User;
echo
$user->name;

namespace
TV ;

class
User
{
    public static
$name = 'tv user';
}

echo \
TV\User::$name;
up
3
TonyMarston at tonymarston dot net
3 years ago
I should point out that namespaces were implemented in PHP to resolve name clashes in userland code. It was never the intention to eventually change the entire language to use namespaces instead of prefixes (ie: change mysqli_connect() to mysqli/connect()) as this would be a huge BC break.

I should also point out that the PSR standards created by the FIG group are *NOT* the official standards for PHP. While there are coding standards for contributing to PHP core, or for creating extensions, there are none for userland developers who are free to adopt whatever standards they choose.
up
-5
Anonymous
3 years ago
php reserve keywords are not allowed as a namespace name.But namespace name "php" can be allowed.

Here are some example:

namespace php;//works
namespace class;//Parse error: syntax error, unexpected 'class'
namespace const;//Parse error: syntax error, unexpected 'const'
namespace constant;//works
namespace interface;//Parse error: syntax error, unexpected 'interface'
namespace function;//Parse error: syntax error, unexpected 'function'
To Top