Php namespace namespace

Source: Internet
Author: User
Tags constant php file php and
Php namespace namespace




The official statement is:
In PHP, namespaces are used to solve two types of problems when creating reusable code such as classes or functions when writing a class library or application
1. User-written code conflicts with the name of a class/function/constant or third party class/function/constant inside PHP.
2. Create an alias (or short) name for a long identifier name (usually defined to mitigate the first type of problem), improving the readability of the source code.
In fact, the namespace is to solve the introduction of different files exist two identical classes, where __namespace__ can get the name of the NAMESPACE.
For example, I have an index file that introduces test.php and test2.php. But all two files contain class take, so that we're in the index.php file
To instantiate the new take will have an error, we need to use namespaces.


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 takes the namespace of the take class in the test file to be aliased to a (pure practice);
Require_once (' test.php ');
Require_once (' test2.php ');


$obj = new A\take (); The take class in the test file
Print " ";
$obj 2 = new My\take (); The take class in the Test2 file


Output results are




This is Test file! Name Is:takes
————————————————————————————————————————————————
This is a My files! Not Test,name Is:my

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.