What is a namespace? In a broad sense, namespace is a way to encapsulate things. This abstract concept can be seen in many places. For example, a directory in the operating system is used to group related files.
Namespace overview
What is a namespace? In a broad sense, namespace is a way to encapsulate things. This abstract concept can be seen in many places. For example, a directory in the operating system is used to group related files. for files in the directory, it plays the role of namespace. For example, the file foo.txt can exist in the/home/greg and/home/other directories at the same time, but there cannot be two foo.txt files in the same directory. In addition, when accessing the foo.txt file outside the/home/greg Directory, we must put the directory name and directory separator before the file name to get/home/greg/foo.txt. This principle is applied to the field of programming as a namespace concept.
In PHP, the namespace is used to solve the two problems encountered when you create reusable code such as classes or functions when writing class libraries or applications:
The user-written code conflicts with the names of PHP internal classes/functions/constants or third-party classes/functions/constants.
Create an alias (or short) name for a long identifier name (usually defined to mitigate the first type of problem) to improve the readability of the source code.
The PHP namespace provides a way to combine related classes, functions, and constants. The following is an example of PHP namespace syntax:
Example #1 namespace syntax Example
PHP versions later than 5.3.0 support namespaces.
Define a namespace
Although any valid PHP code can be included in the namespace, only three types of code are affected by the namespace. they are classes, 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.
Example #1 declare a single namespace
The only valid code before declaring a namespace is the declare statement used to define the source file encoding method. In addition, all non-PHP code, including blank characters, cannot appear before the namespace declaration:
Example #2 declare a single namespace
In addition, unlike other PHP language features, 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
It has a similar relationship with directories and files. The PHP namespace also allows you to specify a hierarchical namespace name. Therefore, namespace names can be defined in different layers:
Example #1 declare a single namespace in different levels
The above example creates the constant MyProject \ Sub \ Level \ CONNECT_ OK, class MyProject \ Sub \ Level \ Connection and function MyProject \ Sub \ Level \ Connection.