Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PHP Namespace

PHP Namespace

PHP namespace was added in PHP 5.3 to solve the problem of name conflicts. PHP does not allow two functions or classes to have the same name; otherwise a fatal error will occur.

PHP namespaces can solve the following two types of problems:

  1. Name conflicts between user-written code and PHP's internal classes/functions/constants or third-party classes/functions/constants.
  2. Create an alias (or short) name for very long identifier names (usually defined to mitigate the first type of problem), improving the readability of the source code.

Defining a namespace

By default, all constant, class, and function names are placed in the global space, just as before PHP supported namespaces.

A namespace is declared using the namespace keyword. If a file contains a namespace, it must declare the namespace before all other code.

The syntax format is as follows:



You can also define code for different namespaces in the same file, for example:



  

It is not recommended to use this syntax to define multiple namespaces in a single file. It is recommended to use the brace-style syntax shown below.





To combine global (non-namespaced) code with namespaced code in a single file, only the brace-style syntax can be used. The global code must be wrapped in a nameless namespace statement with braces, for example:



The only legal code allowed before a namespace declaration is a declare statement that defines the source file's encoding. All non-PHP code, including whitespace, must not appear before the namespace declaration.





The following code will produce a syntax error:





” 会致命错误 - 命名空间必须是程序脚本的第一条语句

?>


Sub-namespaces

Much like directories and files, PHP namespaces also allow hierarchical namespace names. Therefore, namespace names can be defined in a hierarchical manner:





The example above creates the constant MyProject\Sub\Level\CONNECT_OK, the class MyProject\Sub\Level\Connection, and the function MyProject\Sub\Level\Connect.


Namespace Usage

Class names in a PHP namespace can be referenced in three ways:

  1. Unqualified name, or a class name without a prefix,For example $a=new foo(); or foo::staticmethod();. If the current namespace is currentnamespace, foo will be resolved to currentnamespace\foo. If the code using foo is global (not contained in any namespace), then foo will be resolved to foo. Warning: if a function or constant in a namespace is not defined, the unqualified function or constant name will be resolved to the global function or constant name.

  2. Qualified name, or a name that includes a prefix,For example $a = new subnamespace\foo(); or subnamespace\foo::staticmethod();. If the current namespace is currentnamespace, then foo will be resolved to currentnamespace\subnamespace\foo. If the code using foo is global (not contained in any namespace), foo will be resolved to subnamespace\foo.

  3. Fully qualified name, or a name that includes the global prefix operator,For example, $a = new \currentnamespace\foo(); or \currentnamespace\foo::staticmethod();. In this case, foo is always resolved to the literal name currentnamespace\foo as written in the code.

Below is an example that uses these three methods:

Code of file1.php





Code of file2.php





Note that you can use a fully qualified name to access any global class, function, or constant, for example \strlen() or \Exception or \INI_ALL.

Accessing global classes, functions, and constants from within a namespace:






Namespaces and dynamic language features

The implementation of PHP namespaces is affected by the dynamic nature of the language itself. Therefore, when converting the code below into a namespace, dynamically accessed elements...

Code of example1.php:





You must use a fully qualified name (including the namespaced prefix for the class name). Note that within a dynamic class name, function name, or constant name, there is no distinction between a qualified name and a fully qualified name, so the leading backslash is unnecessary.

Dynamically accessing namespaced elements






The namespace keyword and the __NAMESPACE__ constant

PHP supports two abstract ways to access elements within the current namespace:NAMESPACE Magic constants and the namespace keyword.

The value of the constant __NAMESPACE__ is a string containing the name of the current namespace. In global code that is not contained in any namespace, it contains an empty string.

NAMESPACE Example: code within a namespace





NAMESPACE Example: global code





Constant NAMESPACE It is useful when dynamically creating names, for example:

Dynamically creating names using __NAMESPACE__





The namespace keyword can be used to explicitly access elements in the current namespace or a sub-namespace. It is equivalent to the self operator within a class.

The namespace operator, code within a namespace





The namespace operator, global code






Using namespaces: aliases/importing

PHP namespaces support two ways of using aliases or imports: aliasing a class name, or aliasing a namespace name.

In PHP, an alias is created using the use operator. Below is an example that uses all three possible import methods:

1. Importing/using an alias with the use operator





2. Multiple use statements in a single line





The import operation is performed at compile time, but dynamic class, function, or constant names are not.

3. Imports and dynamic names





In addition, the import operation only affects unqualified and qualified names. Fully qualified names are unambiguous and therefore are not affected by imports.

4. Imports and fully qualified names






Using namespaces: fallback global functions/constants

Within a namespace, when PHP encounters an unqualified class, function, or constant name, it uses different priority strategies to resolve that name. Class names are always resolved to the name in the current namespace. Therefore, when accessing system-internal or non-namespaced class names, you must use a fully qualified name, for example:

1. Accessing a global class from within a namespace





For functions and constants, if the function or constant does not exist in the current namespace, PHP falls back to using the function or constant in the global space.

2. Fallback global functions/constants in a namespace






Global space

If no namespace is defined, all class and function definitions live in the global space, just as before PHP introduced the namespace concept. Prefixing a name with \ indicates that the name belongs to the global space, even when that name appears inside another namespace.

Notes on using the global space






Namespace ordering

Since namespaces were introduced, the easiest mistake to make is, when using a class, not knowing what the lookup path for that class actually is.





Name resolution follows these rules:

  1. Calls to fully qualified function, class, and constant names are resolved at compile time. For example new \A\B Resolved as a class A\B.
  2. All unqualified and qualified names (non-fully-qualified names) are transformed at compile time according to the current import rules. For example, if the namespace A\B\C is imported as C, then a call to C\D\e() is transformed into A\B\C\D\e().
  3. Inside a namespace, all qualified names that are not transformed by the import rules will have the current namespace name prepended. For example, in the namespace A\B a call inside C\D\e(), then C\D\e() is transformed into A\B\C\D\e() .
  4. Unqualified class names are transformed at compile time according to the current import rules (the full name replaces the short imported name). For example, if the namespace A\B\C is imported as C, then new C() is transformed into *new A\B\C() *.
  5. Inside a namespace (for example A\B), calls to functions with unqualified names are resolved at runtime. For example, a call to the function foo() is resolved as follows:
    1. Look up the function named A\B\foo() in the current namespace
    2. Try to look up and call global the function in the space foo().
    1. Look up the function named *A\B\foo()* in the current namespace. 2. Try to look up and call the function *foo()* in the *global* space.
    1. Inside a namespace (for exampleA\B) calls to classes with unqualified or qualified names (non-fully-qualified names) are resolved at runtime. The following is the resolution process for a call to new C() and new D\E() Resolution process: * new C()* resolves as:
      1. Look up in the current namespaceA\B\Cthe class.
      2. Try to autoload the classA\B\C.
      * new D\E()* resolves as:
      1. Prepend the current namespace name to the class name, resulting in:A\B\D\E, then look up the class.
      2. Try to autoload the class A\B\D\E.
      To refer to a global class in the global namespace, you must use a fully qualified name *new \C()*. 1. Look up the class *A\B\C* in the current namespace. 2. Try to autoload the class *A\B\C*.
      1. Prepend the current namespace name to the class name, resulting in:A\B\D\E, then look up the class.
      2. Try to autoload the class A\B\D\E.