Basis and Examples of PHP Namespace of namespace
- 2021-07-13 04:36:32
- OfStack
The namespace of PHP (namespace) is the most important new feature added in PHP 5.3. This concept has been around for a long time in C #, and namespace in php is actually the same concept as c #.
1. The namespace of PHP mainly solves three kinds of conflicting problems: constants, functions and classes
Popular understanding: namespace is equivalent to building a directory, and the code below namespace is placed in the directory to distinguish it from the outside.
/*
|---------------------------------
|namespace Example
|@ Black-eyed poet <www.chenwei.ws>
|---------------------------------
*/
namespace myself;
function var_dump()
{
echo 100;
}
var_dump(); // Call custom functions (relative path mode)
\myself\var_dump(); // Call custom functions (absolute path mode)
\var_dump(100); // Call global (system function)
Note: There can be no code before namespace, except declare (); Multiple files can use the same 1 namespace, but the contents defined under the 1 namespace cannot conflict. namespace supports child namespaces, such as namespace\ myself\ good, which is equivalent to the concept of multilevel directories.
2. Multiple namespaces in the same 1 file
1.
/**
* Same as 1 If multiple namespaces are used in the file, ,1 General writing
*/
namespace nihao\shijie;
function demo()
{
//.......
}
namespace hello\world;
function test()
{
//........
}
\nihao\shijie\demo();
\hello\world\test();
2.
/**
* Same as 1 If multiple namespaces are used in the file, it is recommended to enlarge curly braces
*/
namespace nihao\shijie{
function test_one()
{
//......
};
}
namespace hello\world{
function test_two()
{
//........
}
}
\nihao\shijie\test_one();
\hello\world\test_two();
The same 1 file using multiple namespaces, mainly for the project will be a number of PHP scripts merged in the same 1 file, the actual use is not recommended!
3. Name resolution rules (several concepts)
1. Unqualified name: The name does not contain namespace delimiters, such as myself
2. Qualified name: The name contains a namespace delimiter, such as: nihao\ shijie
3. Fully qualified name: The name contains a delimiter and begins with a namespace delimiter, such as:\ nihao\ shijie (that is, the concept of absolute path)