Before discussing how to use a namespace, you must understand how PHP knows the elements in the namespace to be used. A simple analogy can be made between the PHP namespace and the file system. There are three ways to access a file in a file system: before discussing how to use a namespace, you must understand how PHP knows which namespace to use. A simple analogy can be made between the PHP namespace and the file system. There are three methods to access a file in a file system:
The relative file name is similar to foo.txt. It will be parsed to currentdirectory/foo.txt, where currentdirectory indicates the current directory. Therefore, if the current directory is/home/foo, the file name is resolved to/home/foo/foo.txt.
The relative path name format is subdirectory/foo.txt. It will be parsed as currentdirectory/subdirectory/foo.txt.
The absolute path name format is/main/foo.txt. It will be parsed to/main/foo.txt.
Elements in the PHP namespace use the same principle. For example, a class name can be referenced in three ways:
A non-qualified name or a class name that does not contain a prefix, for example, $ a = new foo (); or foo: staticmethod ();. If the current namespace is currentnamespace, foo will be parsed as currentnamespace \ foo. If the code using foo is global and is not included in any namespace, foo will be parsed as foo. Warning if the function or constant in the namespace is not defined, the undefined function name or constant name will be resolved to the global function name or constant name.
A qualified name, or a name containing a prefix, such as $ a = new subnamespace \ foo (); or subnamespace \ foo: staticmethod ();. If the current namespace is currentnamespace, foo will be parsed as currentnamespace \ subnamespace \ foo. If the code using foo is global and is not included in any namespace, foo will be parsed as subnamespace \ foo.
A fully qualified name or a name that contains the global prefix operator, for example, $ a = new \ currentnamespace \ foo (); or \ currentnamespace \ foo: staticmethod ();. In this case, foo is always parsed as the text name (literal name) currentnamespace \ foo in the code.
The following is an example using these three methods:
File1.php:
File2.php:
Note that you can use a fully qualified name to access any global class, function, or constant, such as \ strlen (), \ Exception, or \ INI_ALL.
Example #1 access global classes, functions, and constants within the namespace