Overview
The role of namespaces is to resolve naming conflicts
Define namespaces
Although any valid PHP code can be included in a namespace, only the following types of code are affected by namespaces: classes (including abstract classes and traits), interfaces, functions, and constants.
The namespace is declared by the keyword namespace. If a file contains a namespace, it must declare the namespace before all other code, except one: the DECLARE keyword.
The only valid code before declaring the 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 declaration of the namespace
The same namespace can be defined in multiple files, which allows the content of the same namespace to be split into separate files.
Defining child namespaces
namespace Myproject\sub\level;
Define multiple namespaces in the same file
It is not recommended to use this syntax to define multiple namespaces in a single file. It is recommended to use the following form of curly braces syntax
In practical programming practice, it is highly discouraged to define multiple namespaces in the same file. This approach is primarily used to merge multiple PHP scripts into the same file.
Using namespaces
Elements in a namespace can be accessed through relative paths and absolute paths
file1.php
file2.php
Global space
If no namespace is defined, all classes and functions are defined in the global space, as before the introduction of the namespace concept in PHP. Precede the name with a prefix \ means that the name is the name in the global space, even if the name is in a different namespace
In a namespace, when PHP encounters an unqualified class, function, or constant name, it uses a different precedence policy to resolve the name. The class name always resolves to the name in the current namespace. Therefore, you must use the fully qualified name when accessing the name of a class that is inside the system or that is not included in the namespace
Alias/import
Use aliases for class names, aliases for interfaces, or aliases for namespace names. PHP 5.6 starts by allowing you to import functions or constants or set aliases for them.
Aliases are implemented using the operator use.
Contains multiple use statements in a row
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.