Home > Backend Development > PHP Tutorial > php namespace namespace_PHP tutorial

php namespace namespace_PHP tutorial

WBOY
Release: 2016-07-13 10:31:32
Original
739 people have browsed it

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...
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template