Although any valid PHP code can be included in the namespace, only the following types of code are affected by the namespace: class (including abstract classes and traits), interfaces, functions, and constants. Php.net
(PHP 5> = 5.3.0, PHP 7)
Define a namespace
Although any valid PHP code can be included in the namespace, only the following types of code are affected by the namespace: class (including abstract classes and traits), interfaces, functions, and constants.
If a file contains a namespace, it must declare the namespace before all other code, except for the declare keyword. All non-PHP code, including blank characters, cannot appear before the namespace declaration.
The same namespace can be defined in multiple files, that is, the content of the same namespace can be separated and stored in different files.
Define a sub-namespace
Define multiple namespaces in the same file
Note: in actual programming practices, it is not recommended to define multiple namespaces in the same file!
Use namespace
Class name reference methods:
A non-qualified name (the name does not contain the namespace separator identifier) or a class name that does not contain a prefix. For example, $ a = new foo (); or foo: staticmethod ();. If the current namespace is currentnamespace, foo will be parsed as currentnamespace \ foo. If the code using foo is global and is not included in any namespace, foo will be parsed as foo. ** WARNING **: If the function or constant in the namespace is not defined, the undefined function name or constant name will be resolved to the global function name or constant name.
Name (the name contains the namespace separator identifier), or the name containing the prefix, for example, $ a = new subnamespace \ foo (); or subnamespace \ foo :: staticmethod ();. If the current namespace is currentnamespace, foo will be parsed as currentnamespace \ subnamespace \ foo. If the code using foo is global and is not included in any namespace, foo will be parsed as subnamespace \ foo.
A fully qualified name (the name contains the namespace separator and the identifier that starts with the namespace separator) or contains the name of the global prefix operator. You can use a fully qualified name to access any global class, function, or constant, such as \ strlen () or \ Exception.
Tips:
$a = '\namespacename\classname';$obj = new $a; $a = 'namespacename\classname';$obj = new $a;$b = 'namespacename\funcname';$b(); // prints namespacename\funcname$b = '\namespacename\funcname';$b(); // also prints namespacename\funcname
Use related constants
The constant _ NAMESPACE _ value is a string containing the name of the current NAMESPACE. Globally, code that is not included in any namespace contains an empty string.
Use namespace: Alias/import
The class name is always resolved to the name in the current namespace. Therefore, you must use a fully qualified name to access the class name in the system or that is not included in the namespace.