Home  >  Article  >  Backend Development  >  php namespace namespace_PHP tutorial

php namespace namespace_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:31:32687browse

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 "


";
$obj2 = new mytake(); //take class in test2 file


The output result is




this is test file! name is : takes
——————————————————————————————————————————————
this is a my files! not test,name is : my

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/762933.htmlTechArticlephp namespace namespace The official statement is: In PHP, namespace is used to solve problems when writing class libraries or applications. Two types of problems encountered when creating reusable code such as classes or functions 1. Use...
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