Home  >  Article  >  Backend Development  >  Basics of using php namespaces

Basics of using php namespaces

伊谢尔伦
伊谢尔伦Original
2016-11-23 10:57:06980browse

Before discussing how to use namespaces, you must understand how PHP knows which namespace elements to use. A simple analogy can be made between the PHP namespace and the file system. There are three ways to access a file in the file system:

Relative file name format such as foo.txt. It will be parsed as currentdirectory/foo.txt, where currentdirectory represents the current directory. So if the current directory is /home/foo, the file name is resolved to /home/foo/foo.txt.

The relative path name format is such as subdirectory/foo.txt. It will be parsed as currentdirectory/subdirectory/foo.txt.

The absolute path name is in the form of /main/foo.txt. It will be parsed as /main/foo.txt.

Elements in the PHP namespace use the same principle. For example, a class name can be referenced in three ways:

an unqualified name, or a class name that does not include a prefix, such as $a=new foo(); or foo::staticmethod();. If the current namespace is currentnamespace, foo will be resolved to currentnamespacefoo. If the code using foo is global and does not contain code in any namespace, foo will be resolved as foo. Warning: If a function or constant in the namespace is undefined, the unqualified function or constant name will be resolved to a global function or constant name.

Qualified names, or names containing prefixes, such as $a = new subnamespacefoo(); or subnamespacefoo::staticmethod();. If the current namespace is currentnamespace, foo will be resolved to currentnamespacesubnamespacefoo. If the code using foo is global, code not contained in any namespace, foo will be resolved to subnamespacefoo.

Fully qualified name, or a name that includes a global prefix operator, for example, $a = new currentnamespacefoo(); or currentnamespacefoo::staticmethod();. In this case, foo is always resolved to the literal name currentnamespacefoo in the code.

The following is an example of using these three methods:

file1.php:

file2.php:

Note that to access any global class, function or constant, you can use a fully qualified name, such as strlen() Or Exception or INI_ALL.

Example #1 Access global classes, functions and constants inside a namespace


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn