1 Overview of namespaces
There is a concept of namespaces in C # and Java, and in PHP, namespaces were first added to PHP 5.3, and previous versions did not have this functionality.
1.1 Why should I use a namespace?
When you do a project, a file may introduce multiple files. If you do not use namespaces, you may have a class, function, or constant with the same name in multiple files that you introduce, and you will get an error (a repeating definition).
Take the function as an example and demonstrate the following:
1.1.1 Does not use namespaces:
Operation Result:
1.1.2 Using namespaces:
Modify the b.php file only in the code above, as follows:
Once again, you will not get an error, running the result:
1.2 Using namespace Benefits
In short, it's about resolving code conflicts. Specific as follows:
- Using frames, third-party class libraries, you can avoid conflicts of classes, functions, and constants.
- Can work together to facilitate the development of a project for many people at the same time, improve development efficiency.
2 Define Namespaces
As shown in 1.1.2, once namespace declares a namespace, the subsequent code belongs to that space.
- You cannot have any output before the defined namespace. such as HTML code.
- The only valid code before declaring the namespace is the Declare statement that defines how the source file is encoded, such as: Declare (encoding= ' UTF-8 ');
- Project, the namespace is defined only at the beginning of a PHP file, and only one is defined.
- Typically, the namespace follows the PSR-0 naming convention (the namespace and directory structure remain consistent).
3 Space classification
Divided into two categories: global space and namespaces
3.1 Global Space
The code in the space that is not in the namespace declaration belongs to the global space.
3.2 Namespaces
such as: namespace Think;
such as: namespace Think\controller; This kind of inverted slash, hierarchical, is the sub-namespace.
If you need a class, function, or constant that uses global space in a namespace, you need to add a backslash (representing the global space) when you call it.
4 Use of Namespaces 4.1 access with qualified name, unqualified name
- Unqualified Name: Access the current namespace. (used directly in the current file)
- Qualified name: Similar to relative path, accesses sub-namespaces under the current space, such as: New People\person ();
- Fully qualified name: similar to absolute path, access to global space, such as: New \person (); Instantiate the person class under global space
4.2 Import namespaces, and then directly use the
Syntax: Use namespace, can alias (as alias).
Purpose: Use the classes, functions, and constants of other namespaces in the current file. (When used, do not add a qualified name)
PHP Namespaces (namespace)