PHP namespace (namespace)
PHP namespace (namespace) was added in PHP 5.3
What is a namespace? Broadly speaking, a namespace is a way of encapsulating things. This abstract concept can be found in many places. For example, in the operating system, directories are used to group related files. For files in the directory, it plays the role of a namespace. For example, the file foo.txt can exist in the directories /home/greg and /home/other at the same time, but two foo.txt files cannot exist in the same directory. In addition, when accessing the
foo.txt file outside the directory /home/greg, we must put the directory name and directory separator before the file name to get /home/greg/foo.txt. This principle applied to the field of programming is the concept of
PHP namespace can solve the following two types of problems:
1. User-written code and Name conflicts between PHP internal classes/functions/constants or third-party classes/functions/constants.2. Create an alias (or short) name for a very long identifier name (usually defined to alleviate the first type of problem) to improve the readability of the source code.
Define namespace
By default, all constants, classes and function names are placed in the global space, just like before PHP supported namespaces.The namespace is declared through the keyword namespace. If a file contains a namespace, it must declare the namespace before all other code.
The syntax is as follows:
你也可以在同一个文件中定义不同的命名空间代码,如:The only legal code before declaring a namespace is the declare statement that defines how the source file is encoded. In addition, all non-PHP code including whitespace characters cannot appear before the namespace declaration: and the following code will report an error
” 会致命错误 - 命名空间必须是程序脚本的第一条语句 ?>Namespaces
are very similar to directories and files. PHP namespaces also allow you to specify hierarchical namespace names. Therefore, namespace names can be defined in a hierarchical manner:
The above example creates the constant MyProject\Sub\Level\CONNECT_OK, the class MyProject\Sub\Level\Connection and the function MyProject\Sub\Level \Connect. Namespace usage
Before discussing how to use namespaces, you must understand how PHP knows which elements in the namespace to use. A simple analogy can be made between the PHP namespace and the file system. There are three ways to access a file in the file system:
1. Relative file name format such as foo.txt. It will be parsed as currentdirectory/foo.txt, where currentdirectory represents the current directory. So if the current directory is /home/foo, the filename is resolved to /home/foo/foo.txt.
2. The relative path name is in the form of subdirectory/foo.txt. It will be parsed as currentdirectory/subdirectory/foo.txt.
3. The absolute path name is in the form of /main/foo.txt. It will be parsed as /main/foo.txt.
The same principle applies to elements in the PHP namespace. For example, a class name can be referenced in three ways:
1. An unqualified name, or a class name that does not include the prefix, such as $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 and does not contain code in any namespace, foo will be resolved as foo. Warning: If a function or constant in the namespace is undefined, the unqualified function or constant name is resolved to a global function or constant name.
2. Qualified name, or name containing prefix, such as $a = new subnamespace\foo(); or subnamespace\foo::staticmethod(); . If the current namespace is currentnamespace, foo will be resolved to currentnamespace\subnamespace\foo. If the code using foo is global, code not contained in any namespace, foo will be resolved to subnamespace\foo.
3. Fully qualified name, or a name that includes a 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 in the code.
The following is an example of using these three methods:
Example
Example
Note that to access any global class, function or constant, you can use a fully qualified name, such as \strlen() or \Exception or \INI_ALL.
Access global classes, functions and constants within the namespace:
Namespace and dynamic language features
Implementation of PHP namespace Affected by the dynamic characteristics of its language itself. So if you want to convert the code below into a namespace, access the elements dynamically.
Example
Program running result:
classname::__construct funcname global
Must use a fully qualified name (class name including namespace prefix). Note that the leading backslash is unnecessary because there is no difference between qualified and fully qualified names in dynamic class names, function names, or constant names.
Example
Dynamic access to elements of the namespace
Program running result:
classname::__construct funcname global classname::__construct funcname global namespacename\classname::__construct namespacename\classname::__construct namespacename\funcname namespacename\funcname namespaced namespaced
##namespace keyword and __NAMESPACE__ constant
PHP supports two abstract methods of accessing elements within the current namespace, the __NAMESPACE__ magic constant and the namespace keyword. The value of the constant __NAMESPACE__ is a string containing the name of the current namespace. In global code, not included in any namespace, it contains an empty string.
Example
##__NAMESPACE__Example, in Code in the namespace
Program running result:"MyProject"
Instance
__NAMESPACE__ example, global code Program running result:""
Example
The constant __NAMESPACE__ is useful when creating names dynamically, for example: Use __NAMESPACE__ to create names dynamically The keyword namespace can be used to explicitly access elements in the current namespace or sub-namespace. It is equivalent to the self operator in classes.Example
namespace operator, code in the namespaceExample
namespace operator, global codeUse namespace: alias/import
PHP namespace support has two ways of using aliases or imports: using aliases for class names, or using aliases for namespace names. Note that PHP does not support imported functions or constants. In PHP, aliases are implemented through the operator use. Here is an example using all three possible import methods:1 , Use the use operator to import/use aliases
2. One line contains multiple use statements
3. Import and dynamic names
4. Import and fully qualified names
Use namespace: fallback global functions/constants
When PHP encounters an unqualified class, function, or constant name within a namespace, it uses a different precedence strategy to resolve the name. Class names always resolve to names in the current namespace. Therefore when accessing class names that are internal to the system or not contained in the namespace, you must use the fully qualified name
For example:
1. Access global classes in the namespace
For functions and constants, if the function or constant does not exist in the current namespace, PHP will fall back to using the function or constant in the global space.
2. Backup global functions/constants in the namespace
Global space
If no namespace is defined, all classes and functions are defined in the global space, just like before PHP introduced the namespace concept. Prefixing a name with \ indicates that the name is in the global space, even if the name is in another namespace.
Example
Using the global space description
The order of the namespace
Since the introduction of namespaces, the most error-prone thing is when using a class, what is the search path for this class.
Name resolution follows the following rules:
1. Calls to functions, classes, and constants with fully qualified names are resolved at compile time. For example, new \A\B resolves to class A\B.
2. All unqualified names and qualified names (non-fully qualified names) are converted at compile time according to the current import rules. For example, if namespace A\B\C is imported as C, then calls to C\D\e() will be translated to A\B\C\D\e().
3. Within the namespace, all qualified names that are not converted according to the import rules will be preceded by the current namespace name. For example, if C\D\e() is called within namespace A\B, C\D\e() will be converted to A\B\C\D\e().
4. Unqualified class names are converted at compile time according to the current import rules (full names are used instead of short import names). For example, if namespace A\B\C is imported as C, then new C() is converted to new A\B\C() .
5. Within a namespace (e.g. A\B), function calls to unqualified names are resolved at runtime. For example, the call to function foo() is parsed like this:
1. Find the function named A\B\foo() in the current namespace
2. Try to find and call Function foo() in global space.
6. Calls to unqualified names or qualified name classes (non-fully qualified names) within a namespace (e.g. A\B) are resolved at runtime. The following is the parsing process of calling new C() and new D\E(): Parsing of new C():
1. Find the A\B\C class in the current namespace.
2. Try to automatically load classes A\B\C.
Parsing of new D\E():
3. Add the current namespace name in front of the class name to become: A\B\D\E, and then search for the class.
4. Try to automatically load class A\B\D\E.
In order to reference a global class in the global namespace, the fully qualified name new \C() must be used.