Php namespace. The namespace of the php namespace official statement is: in PHP, namespace is used to solve two problems encountered when you create reusable code such as classes or functions when writing a class library or application. namespace with php namespace
The official statement is:
In PHP, the namespace is used to solve the two problems encountered when you create reusable code such as classes or functions when writing class libraries or applications.
1. the user-written code conflicts with the names of PHP internal classes/functions/constants or third-party classes/functions/constants.
2. create an alias (or short) name for a long identifier name (usually defined to mitigate the first type of problem) to improve the readability of the source code.
In fact, the NAMESPACE aims to solve the problem of introducing two identical classes to different files, where _ namespace _ can get the NAMESPACE name.
For example, I have an index file that introduces test. php and test2.php. but both files contain class take. in this way, in the index. php file
If you instantiate the new take, an error is returned. in this case, 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; // This way, alias the take class namespace in the test file as a (for pure practice );
Require_once ('test. php ');
Require_once ('test2. php ');
$ Obj = new a \ take (); // take class in the test file
Print" ";
$ Obj2 = new my \ take (); // take class in the test2 file
The output result is
This is test file! Name is: takes
------------------------------------------------
This is a my files! Not test, name is: my
The namespace official statement is: in PHP, namespace is used to solve two types of problems encountered when you create reusable code such as classes or functions when writing a class library or application. use...