php namespace namespace
The official statement is:
In PHP, namespaces are used to solve two types of problems encountered when creating reusable code such as classes or functions when writing class libraries or applications
1. There is a name conflict 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.
In fact, the purpose of namespace is to solve the situation where two identical classes exist when different files are introduced. Among them, __NAMESPACE__ can get the name of the namespace.
For example, I have an index file that imports test.php and test2.php. But both files contain class take , so we have it in the index.php file
An error will be reported when instantiating new take. At this time, we need to use the namespace.
test.php
namespace takes;
class take {
function __construct() {
print "this is test file! name is : ". __NAMESPACE__;
}
}
test2.php
namespace my;
class take {
function __construct() {
print "this is a my files! not test,name is : ". __NAMESPACE__;
}
}
index.php
use takes as a; //In this way, the namespace of the take class in the test file is aliased as a (purely for practice);
require_once('test.php');
require_once('test2.php');
$obj = new take(); //take class in test file
print "