PHP 8.3.21 Released!

Definición de los espacios de nombres

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

Aunque el código PHP válido puede estar contenido en un espacio de nombres, solo los siguientes tipos de código pueden ser afectados por los espacios de nombres: las clases (incluyendo las abstractas y los traits), las interfaces, las funciones y las constantes.

Los espacios de nombres se declaran con la palabra clave namespace. Un fichero que contiene un espacio de nombres debe declarar el espacio al principio del fichero, antes de cualquier otro código, con una sola excepción: la palabra clave declare.

Ejemplo #1 Declaración de un espacio de nombres

<?php
namespace MiProyecto;

const
CONECTAR_OK = 1;
class
Conexión { /* ... */ }
function
conectar() { /* ... */ }

?>

Nota: Los nombres completamente calificados (es decir, los nombres que comienzan con un antislash) no están autorizados en las declaraciones de espacios de nombres, ya que tales construcciones se interpretan como expresiones de espacio de nombres relativo.

El único elemento autorizado antes de la declaración de espacio de nombres es la instrucción declare, para definir la codificación del fichero fuente. Además, ningún código no-PHP puede preceder la declaración de espacio de nombres, incluyendo espacios:

Ejemplo #2 Error de declaración de un espacio de nombres

<html>
<?php
namespace MiProyecto; // error fatal - el espacio de nombres debe ser la primera sentencia del script
?>

Además, a diferencia de otras estructuras PHP, el mismo espacio de nombres puede ser definido en varios ficheros, lo que permite dividir el contenido de un espacio de nombres en varios ficheros.

add a note

User Contributed Notes 11 notes

up
210
kuzawinski dot marcin at NOSPAM dot gmail dot com
10 years ago
If your code looks like this:

<?php
namespace NS;
?>

...and you still get "Namespace declaration statement has to be the very first statement in the script" Fatal error, then you probably use UTF-8 encoding (which is good) with Byte Order Mark, aka BOM (which is bad). Try to convert your files to "UTF-8 without BOM", and it should be ok.
up
143
danbettles at yahoo dot co dot uk
16 years ago
Regarding constants defined with define() inside namespaces...

define() will define constants exactly as specified. So, if you want to define a constant in a namespace, you will need to specify the namespace in your call to define(), even if you're calling define() from within a namespace. The following examples will make it clear.

The following code will define the constant "MESSAGE" in the global namespace (i.e. "\MESSAGE").

<?php
namespace test;
define('MESSAGE', 'Hello world!');
?>

The following code will define two constants in the "test" namespace.

<?php
namespace test;
define('test\HELLO', 'Hello world!');
define(__NAMESPACE__ . '\GOODBYE', 'Goodbye cruel world!');
?>
up
83
FatBat
11 years ago
Expanding on @danbettles note, it is better to always be explicit about which constant to use.

<?php
namespace NS;

define(__NAMESPACE__ .'\foo','111');
define('foo','222');

echo
foo; // 111.
echo \foo; // 222.
echo \NS\foo // 111.
echo NS\foo // fatal error. assumes \NS\NS\foo.
?>
up
9
anisgazig at gmail dot com
4 years ago
namespace statement is defined at first of the php files. But
before namespace declaration only three elements allowed.
1.declare statement
2.spaces
3.comments
up
64
huskyr at gmail dot com
15 years ago
"A file containing a namespace must declare the namespace at the top of the file before any other code"

It might be obvious, but this means that you *can* include comments and white spaces before the namespace keyword.

<?php
// Lots
// of
// interesting
// comments and white space

namespace Foo;
class
Bar {
}
?>
up
47
jeremeamia at gmail dot com
15 years ago
You should not try to create namespaces that use PHP keywords. These will cause parse errors.

Examples:

<?php
namespace Project/Classes/Function; // Causes parse errors
namespace Project/Abstract/Factory; // Causes parse errors
?>
up
7
Anonymous
17 years ago
@ RS: Also, you can specify how your __autoload() function looks for the files. That way another users namespace classes cannot overwrite yours unless they replace your file specifically.
up
1
akirasav at gmail dot com
22 days ago
As of PHP 8.1, not only classes (including abstracts and traits), interfaces, functions, and constants are affected by namespaces, but also enums.

<?php

namespace App\Types;

enum
Colors {
case
Red;
case
Green;
}

$reflection = new \ReflectionEnum('App\Types\Colors');
var_dump($reflection->getName()); // string(16) "App\Types\Colors"
var_dump($reflection->getNamespaceName()); // string(9) "App\Types"

?>
up
3
Baptiste
16 years ago
There is nothing wrong with PHP namespaces, except that those 2 instructions give a false impression of package management.
... while they just correspond to the "with()" instruction of Javascript.

By contrast, a package is a namespace for its members, but it offers more (like deployment facilities), and a compiler knows exactly what classes are in a package, and where to find them.
up
-1
anisgazig at gmail dot com
4 years ago
Namespace name are case-insensitive.
namespace App
and
namespace app
are same meaning.

Besides, Namespace keword are case-insensitive.
Namespace App
namespace App
and
NAMESPACE App
are same meaning.
up
-1
dino at tuxweb dot it
2 years ago
Please note that a PHP Namespace declaration cannot start with a number.
It took some time for me to debug...
To Top