PHP Object-oriented programming and design patterns (5)-PHP namespace usage and name resolution rules

Source: Internet
Author: User
Tags aliases

PHP Advanced Programming Learning Note 2014.06.12

Namespaces Overview

PHP supports namespaces at the beginning of the 5.3.0 version. What is a namespace? In a broad sense, namespaces are a way of encapsulating things. This abstract concept can be seen in many places. 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. User-written code conflicts with the name of a class/function/constant or third-party class/function/constant inside PHP.
    2. Creates an alias (or short) name for a very long identifier name (usually defined to alleviate the first type of problem), improving the readability of the source code.

The PHP namespace provides a way to group related classes, functions, and constants together. The following is an example of a PHP namespace syntax:

Define namespaces

Although any valid PHP code can be included in a namespace, only three types of code are affected by the namespace, which are: classes, 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. In addition, unlike other language features in PHP, the same namespace can be defined in multiple files, allowing the content of the same namespace to be split into separate files. Of course you can also define multiple namespaces in the same file.

namespace MyProject; class myclass{    #code ...}

Define child 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:

namespace myproject\helper\http; class myclass{    #code ...}

define multiple namespaces in the same file: There are two ways to declare multiple namespaces in the same file, but in practical programming practice, it is not recommended to define a multi-GE namespace in the same file. This approach is primarily used to merge multiple PHP scripts into the same file. The first method is listed below.

namespace myproject\helper\http; class myclass{    #code ...} namespace myproject\helper\request; class myclass{    #code ...}

However, it is strongly not recommended to use this method, you can refer to the following brace definition method:

namespace myproject\helper\http; {    class  MyClass    {        #code ...    }} namespace myproject\helper\request; {    class  MyClass    {        #code ...    }}

Elements in the PHP namespace use

Before discussing how to use namespaces, you must understand how PHP knows which namespace elements to use. The class name can be referenced in three ways:

    1. Unqualified name, or class name that does not contain a prefix, such as $a =new foo (); or Foo::staticmethod ();. If the current namespace is Currentnamespace,foo, it will be resolved to Currentnamespace\foo. If the code that uses Foo is global and does not contain code in any namespace, Foo is parsed as Foo. Warning: If a function or constant in a namespace is undefined, the unqualified function name or constant name is resolved to the global function name or constant name. For details, see Using namespaces: Fallback global function name/constant name.
    2. A qualified name, or a name that contains a prefix, such as $a = new Subnamespace\foo (); or Subnamespace\foo::staticmethod ();. If the current namespace is Currentnamespace, Foo will be parsed to Currentnamespace\subnamespace\foo. If the code that uses Foo is global and does not contain code in any namespace, Foo is parsed as Subnamespace\foo.
    3. The fully qualified name, or contains the name of the global prefix operator, for example, $a = new \currentnamespace\foo (); or \currentnamespace\foo::staticmethod ();. In this case, Foo is always parsed into the literal name (literal name) Currentnamespace\foo in the code.

Using namespaces: Aliases/imports

Allowing the external fully qualified name to be referenced or imported through an alias is an important feature of the namespace. The PHP namespace supports two ways to use aliases or imports: Use aliases for class names, or use aliases for namespace names. In PHP, aliases are implemented using the operator use.

Note that PHP does not support importing functions or constants.

namespace as another; // The following example is the same as the use My\full\nsname as Nsname Use my\full\nsname; // Import a global class use \arrayobject;

Name resolution rules

Before we describe the name resolution rules, we'll look at some important definitions:

    1. Unqualified names unqualified Name: An identifier in the name that does not contain a namespace delimiter, such as Foo
    2. Qualified name qualified name: The identifier that contains the namespace delimiter in the name, such as Foo\bar
    3. Fully qualified name fully qualified name: an identifier that contains the namespace delimiter and begins with a namespace delimiter, such as \foo\bar. Namespace\foo is also a fully qualified name.

Name resolution follows these rules:

    1. Calls to fully qualified names for functions, classes, and constants are parsed at compile time. For example, new \a\b resolves to class a\b.
    2. All unqualified and qualified names (not fully qualified names) are converted at compile time according to the current import rules. For example, if the namespace a\b\c is imported as C, then the call to C\d\e () is converted to a\b\c\d\e ().
    3. Inside the namespace, all qualified names that are not translated according to the import rule are preceded by the current namespace name. For example, if you call C\d\e () inside the namespace a\b, C\d\e () is converted to a\b\c\d\e ().
    4. Unqualified class names are converted at compile time based on the current import rule (instead of the short import name with the full name). For example, if the namespace a\b\c is imported as C, then new C () is converted to new a\b\c ().
    5. Within a namespace (for example, a\b), a function call to an unqualified name is parsed at run time. For example, the call to function foo () is parsed like this:
      1) Look for a function named A\b\foo () in the current namespace
      2) try to find and invoke the function foo () in global space.
    6. Calls to unqualified or qualified name classes (not fully qualified names) within a namespace (for example, a\b) are resolved at run time. Here is the parsing process for calling new C () and New D\e (): New C ():
      Finds the A\b\c class in the current namespace.
      Attempt to automatically load class a\b\c.

      Parsing of New D\e ():
      Precede the class name with the current namespace name into: A\b\d\e, and then look for the class.
      Attempt to automatically load class a\b\d\e.

      In order to refer to global classes in the global namespace, you must use the fully qualified name new \c ().

Example Name Resolution Example

<?phpnamespace A; UseB\d, C\e asF;//function Callfoo (); //first try calling the function foo () defined in namespace "A"//and then try calling the global function "foo"\foo (); //Call global space function "foo"My\foo (); //call definition in namespace "a\my" in function "foo"F (); //first try calling the function "F" defined in Namespace "a"//and then try calling the global function "F"//class referenceNewB ();//create an object of class ' B ' defined in namespace ' a '///If not found, try to automatically load class "a\b"NewD ();//create an object of class ' D ' defined in namespace ' B ' using import rules//If not found, attempt to automatically load class "B\d"NewF ();//create an object of class ' E ' defined in namespace ' C ' using import rules//If not found, attempt to automatically load class "C\e"New\b ();//create an object that defines the class "B" in the global space//If it is not found, try to automatically load class "B"New\d ();//create an object that defines the class "D" in the global space//If it is not found, try to automatically load class "D"New\f ();//create an object that defines the class "F" in the global space//If it is not found, try to automatically load the class "F"//Call a static method or namespace function in another namespaceB\foo (); //Call namespace "a\b" in function "foo"B:: foo ();//Call the "Foo" Method of Class "B" defined in the namespace "A"//If the class "a\b" is not found, try to automatically load class "a\b"D:: foo ();//using the import rule, call the "Foo" Method of Class "D" defined in Namespace "B"///If the class "b\d" is not found, try to automatically load class "B\d"\b\foo (); //Call the function "foo" in the Namespace "B"\b:: foo ();//Call the "Foo" Method of Class "B" in global space//If class "B" is not found, try to automatically load static methods or functions in class "B"//Current namespacea\b:: foo ();//Call the "Foo" Method of Class "B" defined in the namespace "a\a"///If the class "a\a\b" is not found, try to automatically load class "a\a\b"\a\b:: foo ();//Call the "Foo" Method of Class "B" defined in the namespace "a\b"///If the class "a\b" is not found, try to automatically load class "a\b"?>
Related Article

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.