This article introduces some terms, parsing rules, and application of some advanced functions of PHP namespaces, hoping to help readers use namespaces in projects.
This article introduces some terms, parsing rules, and application of some advanced functions of PHP namespaces, hoping to help readers use namespaces in projects.
The namespace of PHP is one of the most important new features added to PHP 5.3. This concept has been available in C # for a long time, the namespace in php is actually the same as that in c.
I. PHP namespace mainly solves three types of conflicts: constants, functions, and classes.
In general, namespace is equivalent to creating a directory. The Code under namespace is put in this directory, which is differentiated from that outside.
/* | ----------------------------- | Namespace example | @ <> | example */namespace myself; function var_dump () {echo 100;} var_dump (); // call a custom function (relative path) \ myself \ var_dump (); // call a custom function (absolute path) \ var_dump (100 ); // call global (system function)
Note: No code exists before namespace, except declare (). Multiple files can use the same namespace, but the content defined under the same namespace cannot conflict. Namespace supports sub-namespaces, such as namespace \ myself \ good, which is equivalent to the concept of multi-level directories.
2. multiple namespaces exist in the same file.
1.
/*** If multiple namespaces are used in the same file, use the formula */namespace nihao \ shijie; function demo (){//.......} namespace hello \ world; function test (){//........} \ nihao \ shijie \ demo (); \ hello \ world \ test ();
2.
/*** If multiple namespaces are used in the same file, we recommend that you expand the braces */namespace nihao \ shijie {function test_one () {//......};} namespace hello \ world {function test_two (){//........}} \ nihao \ shijie \ test_one (); \ hello \ world \ test_two ();
Multiple namespaces are used in the same file. They are mainly used in projects to merge multiple PHP scripts into the same file. In practice, they are not recommended!
Iii. name resolution rules (several concepts)
1. Unrestricted name: the name does not contain a namespace separator, for example, myself.
2. Limited name: The name contains a namespace separator, for example, nihao \ shijie
3. Fully qualified name: The name contains a delimiter and starts with a namespace delimiter, for example, \ nihao \ shijie (the concept of absolute path)