array ( 0 => 'index.php', 1 => 'PHP Manual', ), 'head' => array ( 0 => 'UTF-8', 1 => 'en', ), 'this' => array ( 0 => 'language.namespaces.definition.php', 1 => 'Namespaces', ), 'up' => array ( 0 => 'language.namespaces.php', 1 => 'Namespaces', ), 'prev' => array ( 0 => 'language.namespaces.rationale.php', 1 => 'Overview', ), 'next' => array ( 0 => 'language.namespaces.nested.php', 1 => 'Sub-namespaces', ), 'alternatives' => array ( ), 'source' => array ( 'lang' => 'en', 'path' => 'language/namespaces.xml', ), ); $setup["toc"] = $TOC; $setup["toc_deprecated"] = $TOC_DEPRECATED; $setup["parents"] = $PARENTS; manual_setup($setup); ?>
(PHP 5 >= 5.3.0, PHP 7, PHP 8)
Although any valid PHP code can be contained within a namespace, only the following types of code are affected by namespaces: classes (including abstracts and traits), interfaces, functions and constants.
Namespaces are declared using the namespace
keyword. A file containing a namespace must declare the namespace
at the top of the file before any other code - with one exception: the
declare keyword.
Example #1 Declaring a single namespace
<?php
namespace MyProject;
const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */ }
?>
The only code construct allowed before a namespace declaration is theNote: Fully qualified names (i.e. names starting with a backslash) are not allowed in namespace declarations, because such constructs are interpreted as relative namespace expressions.
declare
statement, for defining encoding of a source file. In addition,
no non-PHP code may precede a namespace declaration, including extra whitespace:
Example #2 Declaring a single namespace
<html>
<?php
namespace MyProject; // fatal error - namespace must be the first statement in the script
?>
In addition, unlike any other PHP construct, the same namespace may be defined in multiple files, allowing splitting up of a namespace's contents across the filesystem.