NamespacesNamespaces overviewOverview
What are namespaces? In the broadest definition namespaces are a way of encapsulating
items. This can be seen as an abstract concept in many places. For example, in any
operating system directories serve to group related files, and act as a namespace for
the files within them. As a concrete example, the file foo.txt can
exist in both directory /home/greg and in /home/other,
but two copies of foo.txt cannot co-exist in the same directory. In
addition, to access the foo.txt file outside of the
/home/greg directory, we must prepend the directory name to the file
name using the directory separator to get /home/greg/foo.txt. This
same principle extends to namespaces in the programming world.
In the PHP world, namespaces are designed to solve two problems that authors
of libraries and applications encounter when creating re-usable code elements
such as classes or functions:
Name collisions between code you create, and
internal PHP classes/functions/constants or third-party classes/functions/constants.
Ability to alias (or shorten) Extra_Long_Names designed to alleviate the first problem,
improving readability of source code.
PHP Namespaces provide a way in which to group related classes, interfaces,
functions and constants. Here is an example of namespace syntax in PHP:
Namespace syntax example
]]>
Namespace names are case-insensitive.
The Namespace name PHP, and compound names starting
with this name (like PHP\Classes) are reserved for internal language use
and should not be used in the userspace code.
Defining namespacesNamespaces
Although any valid PHP code can be contained within a namespace, only the following
types of code are affected by namespaces: classes (including abstract classes, traits and enums), 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
keyword.
Declaring a single namespace
]]>
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.
The only code construct allowed before a namespace declaration is the
declare statement, for defining encoding of a source file. In addition,
no non-PHP code may precede a namespace declaration, including extra whitespace:
Declaring a single namespace
]]>
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.
Declaring sub-namespacesSub-namespaces
Much like directories and files, PHP namespaces also contain the ability to specify
a hierarchy of namespace names. Thus, a namespace name can be defined with
sub-levels:
Declaring a single namespace with hierarchy
]]>
The above example creates constant MyProject\Sub\Level\CONNECT_OK,
class MyProject\Sub\Level\Connection and function
MyProject\Sub\Level\connect.
Defining multiple namespaces in the same fileDefining multiple namespaces in the same file
Multiple namespaces may also be declared in the same file. There are two allowed
syntaxes.
Declaring multiple namespaces, simple combination syntax
]]>
This syntax is not recommended for combining namespaces into a single file.
Instead it is recommended to use the alternate bracketed syntax.
Declaring multiple namespaces, bracketed syntax
]]>
It is strongly discouraged as a coding practice to combine multiple namespaces into
the same file. The primary use case is to combine multiple PHP scripts into the same
file.
To combine global non-namespaced code with namespaced code, only bracketed syntax is
supported. Global code should be
encased in a namespace statement with no namespace name as in:
Declaring multiple namespaces and unnamespaced code
]]>
No PHP code may exist outside of the namespace brackets except for an opening
declare statement.
Declaring multiple namespaces and unnamespaced code
]]>
Using namespaces: BasicsBasics
Before discussing the use of namespaces, it is important to understand how PHP
knows which namespaced element your code is requesting. A simple analogy can be made
between PHP namespaces and a filesystem. There are three ways to access a file in a
file system:
Relative file name like foo.txt. This resolves to
currentdirectory/foo.txt where currentdirectory is the
directory currently occupied. So if the current directory is
/home/foo, the name resolves to /home/foo/foo.txt.
Relative path name like subdirectory/foo.txt. This resolves
to currentdirectory/subdirectory/foo.txt.
Absolute path name like /main/foo.txt. This resolves
to /main/foo.txt.
The same principle can be applied to namespaced elements in PHP. For
example, a class name can be referred to in three ways:
Unqualified name, or an unprefixed class name like
$a = new foo(); or
foo::staticmethod();. If the current namespace is
currentnamespace, this resolves to
currentnamespace\foo. If
the code is global, non-namespaced code, this resolves to foo.
One caveat: unqualified names for functions and constants will
resolve to global functions and constants if the namespaced function or constant
is not defined. See Using namespaces:
fallback to global function/constant for details.
Qualified name, or a prefixed class name like
$a = new subnamespace\foo(); or
subnamespace\foo::staticmethod();. If the current namespace is
currentnamespace, this resolves to
currentnamespace\subnamespace\foo. If
the code is global, non-namespaced code, this resolves to subnamespace\foo.
Fully qualified name, or a prefixed name with global prefix operator like
$a = new \currentnamespace\foo(); or
\currentnamespace\foo::staticmethod();. This always resolves
to the literal name specified in the code, currentnamespace\foo.
Here is an example of the three kinds of syntax in actual code:
file1.php
]]>
file2.php
]]>
Note that to access any global
class, function or constant, a fully qualified name can be used, such as
\strlen or \Exception or
\INI_ALL.
Accessing global classes, functions and constants from within a namespace
]]>
Namespaces and dynamic language featuresNamespaces and dynamic language features
PHP's implementation of namespaces is influenced by its dynamic nature as a programming
language. Thus, to convert code like the following example into namespaced code:
Dynamically accessing elementsexample1.php:
]]>
One must use the fully qualified name (class name with namespace prefix).
Note that because there is no difference between a qualified and a fully qualified Name
inside a dynamic class name, function name, or constant name, the leading backslash is
not necessary.
Dynamically accessing namespaced elements
]]>
Be sure to read the note about
escaping namespace names in strings.
The namespace keyword and __NAMESPACE__ magic constantnamespace keyword and __NAMESPACE__
PHP supports two ways of abstractly accessing elements within the current namespace,
the __NAMESPACE__ magic constant, and the namespace
keyword.
The value of __NAMESPACE__ is a string that contains the current
namespace name. In global, un-namespaced code, it contains an empty string.
__NAMESPACE__ example, namespaced code
]]>
__NAMESPACE__ example, global code
]]>
The __NAMESPACE__ constant is useful for dynamically constructing
names, for instance:
using __NAMESPACE__ for dynamic name construction
]]>
The namespace keyword can be used to explicitly request
an element from the current namespace or a sub-namespace. It is the namespace
equivalent of the self operator for classes.
the namespace operator, inside a namespace
]]>
the namespace operator, in global code
]]>
Using namespaces: Aliasing/ImportingAliasing and Importing
The ability to refer to an external fully qualified name with an alias, or importing,
is an important feature of namespaces. This is similar to the
ability of unix-based filesystems to create symbolic links to a file or to a directory.
PHP can alias(/import) constants, functions, classes, interfaces, traits, enums and namespaces.
Aliasing is accomplished with the use operator.
Here is an example showing all 5 kinds of importing:
importing/aliasing with the use operator
]]>
Note that for namespaced names (fully qualified namespace names containing
namespace separator, such as Foo\Bar as opposed to global names that
do not, such as FooBar), the leading backslash is unnecessary and not
recommended, as import names
must be fully qualified, and are not processed relative to the current namespace.
PHP additionally supports a convenience shortcut to place multiple use statements
on the same line
importing/aliasing with the use operator, multiple use statements combined
]]>
Importing is performed at compile-time, and so does not affect dynamic class, function
or constant names.
Importing and dynamic names
]]>
In addition, importing only affects unqualified and qualified names. Fully qualified
names are absolute, and unaffected by imports.
Importing and fully qualified names
]]>
Scoping rules for importing
The use keyword must be declared in the
outermost scope of a file (the global scope) or inside namespace
declarations. This is because the importing is done at compile
time and not runtime, so it cannot be block scoped. The following
example will show an illegal use of the use
keyword:
Illegal importing rule
]]>
Importing rules are per file basis, meaning included files will
NOT inherit the parent file's importing rules.
Group use declarations
Classes, functions and constants being imported from
the same &namespace; can be grouped together in a single &use.namespace;
statement.
Global spaceGlobal space
Without any namespace definition, all class and function definitions are
placed into the global space - as it was in PHP before namespaces were
supported. Prefixing a name with \ will specify that
the name is required from the global space even in the context of the
namespace.
Using global space specification
]]>
Using namespaces: fallback to the global space for functions and constantsFallback to global space
Inside a namespace, when PHP encounters an unqualified Name in a class name, function or
constant context, it resolves these with different priorities. Class names always
resolve to the current namespace name. Thus to access internal or non-namespaced
user classes, one must refer to them with their fully qualified Name as in:
Accessing global classes inside a namespace
]]>
For functions and constants, PHP will fall back to global functions or constants
if a namespaced function or constant does not exist.
global functions/constants fallback inside a namespace
]]>
Name resolution rulesName resolution rules
For the purposes of these resolution rules, here are some important definitions:
Namespace name definitionsUnqualified name
This is an identifier without a namespace separator, such as FooQualified name
This is an identifier with a namespace separator, such as Foo\BarFully qualified name
This is an identifier with a namespace separator that begins with a
namespace separator, such as \Foo\Bar. The namespace
\Foo is also a fully qualified name.
Relative name
This is an identifier starting with namespace, such as
namespace\Foo\Bar.
Names are resolved following these resolution rules:
Fully qualified names always resolve to the name without leading namespace separator.
For instance \A\B resolves to A\B.
Relative names always resolve to the name with namespace replaced by
the current namespace. If the name occurs in the global namespace, the
namespace\ prefix is stripped. For example namespace\A
inside namespace X\Y resolves to X\Y\A. The same name
inside the global namespace resolves to A.
For qualified names the first segment of the name is translated according to the current
class/namespace import table. For example, if the namespace A\B\C is
imported as C, the name C\D\E is translated to
A\B\C\D\E.
For qualified names, if no import rule applies, the current namespace is prepended to the
name. For example, the name C\D\E inside namespace A\B,
resolves to A\B\C\D\E.
For unqualified names, the name is translated according to the current import table for the
respective symbol type. This means that class-like names are translated according to the
class/namespace import table, function names according to the function import table and
constants according to the constant import table. For example, after
use A\B\C; a usage such as new C() resolves to the name
A\B\C(). Similarly, after use function A\B\foo; a usage
such as foo() resolves to the name A\B\foo.
For unqualified names, if no import rule applies and the name refers to a class-like symbol,
the current namespace is prepended. For example new C() inside namespace
A\B resolves to name A\B\C.
For unqualified names, if no import rule applies and the name refers to a function or constant
and the code is outside the global namespace, the name is resolved at runtime.
Assuming the code is in namespace A\B, here is how a call to function
foo() is resolved:
It looks for a function from the current namespace:
A\B\foo().
It tries to find and call the global function
foo().
Name resolutions illustrated
]]>
FAQ: things you need to know about namespacesFAQ
This FAQ is split into two sections: common questions, and some specifics of
implementation that are helpful to understand fully.
First, the common questions.
If I don't use namespaces, should
I care about any of this?
How do I use internal or global
classes in a namespace?
How do I use namespaces classes
functions, or constants in their own namespace?
How does a name like \my\name or \name
resolve?
How does a name like
my\name resolve?
How does an unqualified class name
like name resolve?
How does an unqualified function
name or unqualified constant name
like name resolve?
There are a few implementation details of the namespace implementations
that are helpful to understand.
Import names must not conflict with
classes defined in the same file.
Nested namespaces are not allowed.
Dynamic namespace names (quoted
identifiers) should escape backslash.
Undefined Constants referenced
using any backslash die with fatal error
Cannot override special
constants &null;, &true; or &false;
If I don't use namespaces, should I care about any of this?
No. Namespaces do not affect any existing code in any way, or any
as-yet-to-be-written code that does not contain namespaces. You can
write this code if you wish:
Accessing global classes outside a namespace
]]>
This is functionally equivalent to:
Accessing global classes outside a namespace
]]>
How do I use internal or global classes in a namespace?Accessing internal classes in namespaces
]]>
How do I use namespaces classes, functions, or constants in their own
namespace?
Accessing internal classes, functions or constants in namespaces
]]>
How does a name like \my\name or \name
resolve?
Names that begin with a \ always resolve to what they
look like, so \my\name is in fact my\name,
and \Exception is Exception.
Fully Qualified names
]]>
How does a name like my\name resolve?
Names that contain a backslash but do not begin with a backslash like
my\name can be resolved in 2 different ways.
If there is
an import statement that aliases another name to my, then
the import alias is applied to the my in my\name.
Otherwise, the current namespace name is prepended to my\name.
Qualified names
]]>
How does an unqualified class name like name resolve?
Class names that do not contain a backslash like
name can be resolved in 2 different ways.
If there is
an import statement that aliases another name to name, then
the import alias is applied.
Otherwise, the current namespace name is prepended to name.
Unqualified class names
]]>
How does an unqualified function name or unqualified constant name
like name resolve?
Function or constant names that do not contain a backslash like
name can be resolved in 2 different ways.
First, the current namespace name is prepended to name.
Finally, if the constant or function name does not exist
in the current namespace, a global constant or function name
is used if it exists.
Unqualified function or constant names
]]>
Import names must not conflict with classes defined in the same file.
The following script combinations are legal:
file1.php
]]>
another.php
]]>
file2.php
]]>
There is no name conflict, even though the class MyClass exists
within the my\stuff namespace, because the MyClass definition is
in a separate file. However, the next example causes a fatal error on name conflict
because MyClass is defined in the same file as the use statement.
]]>
Nested namespaces are not allowed.
PHP does not allow nesting namespaces
]]>
However, it is easy to simulate nested namespaces like so:
]]>
Dynamic namespace names (quoted identifiers) should escape backslash
It is very important to realize that because the backslash is used as an escape character
within strings, it should always be doubled when used inside a string. Otherwise
there is a risk of unintended consequences:
Dangers of using namespaced names inside a double-quoted string
]]>
Inside a single-quoted string, the backslash escape sequence is much safer to use, but it
is still recommended practice to escape backslashes in all strings as a best practice.
Undefined Constants referenced using any backslash die with fatal error
Any undefined constant that is unqualified like FOO will
produce a notice explaining that PHP assumed FOO was the value
of the constant. Any constant, qualified or fully qualified, that contains a
backslash will produce a fatal error if not found.
Undefined constants
]]>
Cannot override special constants &null;, &true; or &false;
Any attempt to define a namespaced constant that is a special, built-in constant
results in a fatal error
Undefined constants
]]>