PHP Namespaces namespace_php Tutorial

Source: Internet
Author: User
Php namespace namespace




The official statement is:
In PHP, namespaces are used to solve two types of problems encountered when writing a class library or application to create reusable code such as a class or function
1. User-written code conflicts with the name of a class/function/constant or third-party class/function/constant within PHP.
2. Create an alias (or short) name for a very long identifier name (usually defined to alleviate the first type of problem) and improve the readability of the source code.
In fact, the namespace is to solve the introduction of different files exist two the same class, where __namespace__ can get the name of NAMESPACE.
For example, I have an index file that introduces test.php and test2.php. But these two files contain class take, so we're in the index.php file.
To instantiate the new take will be an error, and then 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; The namespace of the take class in the test file is then aliased to a (purely practice);
Require_once (' test.php ');
Require_once (' test2.php ');


$obj = new A\take (); Take class in the test file
Print " ";
$obj 2 = 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

http://www.bkjia.com/PHPjc/762933.html www.bkjia.com true http://www.bkjia.com/PHPjc/762933.html techarticle php namespace namespace The official saying is that in PHP, namespaces are used to solve two types of problems encountered when writing a class library or application to create reusable code such as classes or functions 1. With ...

  • 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.