PHP's namespace

Source: Internet
Author: User
Tags aliases

Previous words

In a broad sense, namespaces are a way of encapsulating things. This abstract concept can be seen in many places. For example, in an operating system, a directory is used to group related files, and for files in a directory, it plays the role of a namespace. This principle is applied to the design field, which is the concept of namespaces.

In PHP, namespaces are used to address two types of problems encountered when creating reusable code such as classes or functions when writing a class library or application: A user-written code that conflicts with the name of a class/function/constant or third-party class/function/constant within PHP, and a long identifier name ( Usually defined to alleviate the first type of problem) create an alias (or short) name to improve the readability of the source code. The PHP namespace provides a way to group related classes, functions, and constants together. This article describes the PHP namespace in detail


Defined

Although any valid PHP code can be included in a namespace, only the following types of code are affected by the namespace: classes (including abstract classes and traits), interfaces, functions, and constants

The namespace is declared by the keyword namespace. If a file contains a namespace, it must declare the namespace before all other code, except one: Declare keyword

<? phpnamespace MyProject; Const CONNECT_OK = 1; class /*  */  }function/**/  }?>

Sub-namespaces

As with directories and files, the PHP namespace allows you to specify the name of a hierarchical namespace. Therefore, the name of the namespace can be defined in a hierarchical way

<? phpnamespace Myproject\sub\level; Const CONNECT_OK = 1; class /*  */  }function/**/  }?>
<? php    namespace myproject\sub\level;     Const NUM = 1;     Echo NUM; // 1 echo \myproject\sub\level\num;//1?>

Multi-namespace

You can define multiple namespaces in the same file. There are two syntactic forms of defining multiple namespaces in the same file

In practical programming practice, it is highly discouraged to define multiple namespaces in the same file. This approach is primarily used to merge multiple PHP scripts into the same file

"1" Simple combination syntax (not recommended)

<?phpnamespace MyProject;ConstCONNECT_OK = 1;classConnection {/* ... */ }functionConnect () {/* ... */}namespace Anotherproject;ConstCONNECT_OK = 1;classConnection {/* ... */ }functionConnect () {/* ... */  }?>

"2" Curly brace syntax

<?phpnamespace MyProject {ConstCONNECT_OK = 1;classConnection {/* ... */ }functionConnect () {/* ... */}}namespace Anotherproject {ConstCONNECT_OK = 1;classConnection {/* ... */ }functionConnect () {/* ... */  }}?>
<? phpnamespace MyProject {    const NUM = 1;} namespace Anotherproject {    const NUM = 2;     Echo NUM; // 2 echo \myproject\num;//1}? >

Global

The code in the global non-namespace is combined with the code in the namespace, and only the syntax in the form of braces is used. The global code must be enclosed in curly braces with a namespace statement without a name

 <? phpnamespace MyProject { const  CONNECT_OK = 1 class  Connection {/*   ...  */  " function  Connect () {/*   ...  */  }}namespace { //  Global code  session_start   ();   $a  = Myproject\connect ();  echo  Myproject\connection::start ();} ? 

Name resolution

Unqualified names unqualified name refers to identifiers that do not contain a namespace delimiter in the name, such as Foo

The qualified name qualified name refers to the identifier that contains the namespace delimiter in the name, such as Foo\bar

The fully qualified name fully qualified name refers to the identifier that contains the namespace delimiter in the name and begins with the namespace delimiter, such as \foo\bar. Namespace\foo is also a fully qualified name

If you want to dynamically access an element (for example, a variable function), you must use the fully qualified name

<? phpnamespace MyProject;     function Test () {        echo ' 111 ';    }     $var 1 = ' test ';     $var 2 = ' \myproject\test ';     $var 1 (); // error $var 2 ();/111?>

accessing internal elements

PHP supports two abstract methods for accessing elements inside the current namespace, __namespace__ Magic constants and NAMESPACE keywords

The value of the constant __namespace__ is a string containing the name of the current namespace. In the global, not included in any namespace code, it contains an empty string

<? phpnamespace MyProject;     function Test () {        echo ' 111 ';    }     $var = __namespace__. ' \test ';     $var (); // 111?>

The keyword namespace can be used to explicitly access elements in the current namespace or in a sub-namespace. It is equivalent to the self operator in a class

<? phpnamespace MyProject;     function Test () {        echo ' 111 ';    }    Test (); // 111 __namespace__.test ();//111 namespace\test ();//111?>

Global space

If no namespace is defined, all classes and functions are defined in the global space, as before the introduction of the namespace concept in PHP. Precede the name with a prefix \ means that the name is the name in the global space, even if the name is in a different namespace

<? phpnamespace a\b\c; /*  */functionfopen()      {/**/$f = \fopen//  Call the global fopen function return $f;  ?>

Aliases and imports

PHP allows the use of aliases to reference or import externally qualified names, which is an important feature of the namespace. This is somewhat similar to the ability to create symbolic connections to other files or directories in a UNIX-like file system

All PHP versions that support namespaces support three aliases or imports: Use aliases for class names, use aliases for interfaces, or use aliases for namespace names

In PHP, aliases are implemented using the operator use.

Alias

<? phpnamespace hello\world\test;  Use  as T; // use T to replace Hello\world\test function demo () {    Echo ' 111 ';} T\demo (); // 111?>

As can be omitted

<? phpnamespace hello\world\test;  use hello\world\test; // use test to replace Hello\world\test function demo () {    Echo ' 111 ';} Test\demo (); // 111?>

Import

<? PHP  Use \arrayobject; $a New Arrayobject ([]); // If use \arrayobject is not used, a Foo\arrayobject object is instantiated?>

To simplify, a row can contain multiple use statements

<? PHP  Use  as Another, My\full\nsname; $obj New // Instantiate My\full\classname object Nsname\subns\func ();//Call function My\full\nsname\subns\func?>

PHP's namespace

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.