Home > Article > Backend Development > PHP namespace concept analysis, php namespace analysis_PHP tutorial
What is a namespace? "Broadly speaking, a namespace is a way of encapsulating things. This abstract concept can be seen in many places. For example, in operating systems, directories are used to group related files. For files in a 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. , 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 is applied to the field of programming as namespaces. Concept." - Namespace Overview
In essence, a namespace is a container. We can put classes, functions and variables into this container, and they can access each other unconditionally in the same namespace. Outside the namespace, other namespaces must be referenced or imported in order to call the items they contain.
The concept of namespace is the same as the file directory in the shell. You can directly access all files by file name in the current directory. If you need to access files in other directories, you need to enter a relative path or an absolute path.
Citation method:
namespace foo; class Foo { public function foo() { return \top\namespace\bar\Bar::fuck(); } }
Import method:
namespace foo; use top\namespace\bar\Bar; class Foo { public function foo() { return Bar::fuck(); } }
Importing is equivalent to copying the target class into the current namespace.
The existence of namespace is to solve the following two problems:
1. Name conflicts between user-written code and 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.
1. Classes in the same space call each other directly and belong to the same family. For example, in the PageController class in Laravel, you can directly write code like Page::all() to call the Page model, because both of them are under the top-level namespace.
2. If a class exists in a non-top-level namespace, it can only call other classes in the current namespace without "referencing" or "importing". They belong to the same family. Any subnamespace is another namespace, another container, without any special relationship other than that between containers.
3. Laravel uses the classmap method for automatic loading (autoload). Although PHP has the advanced feature of namespace, this is only a logical relationship, and the require file is still required. The corresponding relationship between this class and the file exists in /vendor/composer/autoload_classmap.php, and composer dump-autoload will be recompiled and generated every time.