PHP namespaces

Source: Internet
Author: User

Tags: encoding according to Ted default Exce imp includes fopen const

PHP Namespaces (namespace)

PHP namespaces (namespace) are added in PHP 5.3, and if you learn C # and Java, that namespace is nothing new. However, in PHP there is a very important meaning.

The PHP namespace resolves the following two types of problems:

    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.

Define namespaces

By default, all constants, classes, and function names are placed in the global space, just as they were before PHP supported namespaces.

The namespace is declared by the keyword namespace. If a file contains a namespace, it must declare the namespace before all other code. The syntax format is as follows;

< PHP  //Definition code namespace MyProject in the ' MyProject ' namespace  ;   // ... Code...? >

  

You can also define different namespace codes in the same file, such as:

< PHP namespace MyProject1; PHP code in the MyProject1 namespace namespace MyProject2; PHP code in the MyProject2 namespace//Another syntax namespace MyProject3 {//MyProject3 PHP code in namespace}?>

  

The only valid code before declaring the namespace is the Declare statement that defines how the source file is encoded. All non-PHP code, including whitespace characters, cannot appear before the declaration of the namespace.

<?phpdeclare (encoding= ' UTF-8 '); Define multiple namespaces and code that is not included in the namespace namespace MyProject {Const CONNECT_OK = 1;class Connection {/* ... */}function CONNECT () {/*. . *  /}}namespace {//Global code session_start (); $a = Myproject\connect (); Echo Myproject\connection::start ();}? >

  

The following code will cause a syntax error:

<html><?phpnamespace MyProject; <html> fatal error before namespace-The namespace must be the first statement of the program script?>

  

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;  Declares a hierarchical single namespace const CONNECT_OK = 1; Const is the constant modifier class Connection {/* ... */}function Connect () {/* ... */  }?>

  

The above example creates constants Myproject\sub\level\connect_ok, class Myproject\sub\level\connection, and function Myproject\sub\level\connect.

namespaces use

Class names in the PHP namespace 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. (That is, if functions, constants, and classes are not defined in the namespace, PHP defaults to global functions, constants, classes)

    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.

Here is an example of using these three ways:

file1.php File Code

<?phpnamespace Foo\bar\subnamespace; const FOO = 1;function foo () {}class foo{    static function Staticmethod () {}}?>

  

file2.php File Code

<?phpnamespace foo\bar;include ' file1.php '; const FOO = 2;function foo () {}class foo{    static function Staticmethod () {}}/* unqualified name */foo (); resolves to foo\bar\foo resolves to function foo\bar\foofoo::staticmethod (); A static method staticmethod that resolves to a class foo\bar\foo. resolves to class Foo\bar\foo, method Staticmethodecho Foo; Resolves to constant foo\bar\foo/* limited name */subnamespace\foo (); Parse to function Foo\bar\subnamespace\foosubnamespace\foo::staticmethod (); Parse to Class Foo\bar\subnamespace\foo,/                                  /and methods of class Staticmethodecho Subnamespace\foo;//resolve to constant Foo\bar\subnamespace\foo /                                  * Fully qualified name */\foo\bar\foo ();//parse to function Foo\bar\foo\foo\bar\foo::staticmethod ();//Parse to Class Foo\bar\foo, and methods of class Staticmethodecho \foo\bar\foo; Resolve to constant foo\bar\foo?>

  

Note Access to any global class, function, or constant can use a fully qualified name, such as \strlen () or \exception or \ini_all.

Access global classes, functions, and constants inside the namespace:

<?phpnamespace foo;function strlen () {}const Ini_all = 3;class Exception {} $a = \strlen (' Hi '); Call global function strlen$b = \ini_all; Access Global Constants Ini_all$c = new \exception (' Error '); Instantiate Global class Exception?>

  

Namespaces and dynamic Language features

The implementation of the PHP namespace is influenced by the dynamic characteristics of its language itself. Therefore, if you want to convert the following code into a namespace, the element is dynamically accessed.

example1.php File Code:

<?phpclass classname{    function __construct ()    {        echo __method__, ' \ n ';    }} function FuncName () {    echo __function__, ' \ n ';} Const CONSTNAME = "global"; $a = ' classname '; $obj = new $a; Prints classname::__construct$b = ' funcname '; $b (); Prints Funcnameecho constant (' constname '), "\ n"; Prints global?>

  

You must use the fully qualified name (including the class name of the namespace prefix). Note Because the qualified name and the fully qualified name do not differ in the dynamic class name, function name, or constant name, the leading backslash is unnecessary.

Dynamically accessing elements of a namespace

<?phpnamespace namespacename;class classname{    function __construct ()    {        echo __method__, ' \ n ';    }} function FuncName () {    echo __function__, ' \ n ';} Const CONSTNAME = "namespaced"; include ' example1.php '; $a = ' classname '; $obj = new $a; Prints classname::__construct$b = ' funcname '; $b (); Prints Funcnameecho constant (' constname '), "\ n"; Prints global/* Note that if using a double quotes, "\\namespacename\\classname" must be used */$a = ' \namespacename\clas Sname '; $obj = new $a; Prints namespacename\classname::__construct$a = ' namespacename\classname '; $obj = new $a; Also prints namespacename\classname::__construct$b = ' namespacename\funcname '; $b (); Prints namespacename\funcname$b = ' \namespacename\funcname '; $b (); Also prints Namespacename\funcnameecho constant (' \namespacename\constname '), "\ n"; Prints Namespacedecho constant (' namespacename\constname '), "\ n"; Also prints namespaced?>

  

NAMESPACE keywords and __namespace__ constants

PHP supports two abstract methods of accessing the inner elements of 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.

__namespace__ example, code in a namespace

<?phpnamespace Myproject;echo ' "', __namespace__, '"; Output "MyProject"? >__namespace__ example, Global code <?phpecho ' ' ', __namespace__, ' "; The output ""?> constant __namespace__ is useful when creating names dynamically, for example: Create names dynamically using __namespace__ <?phpnamespace myproject;function get ($ ClassName) {    $a = __namespace__. ‘\\‘ . $classname;    return new $a;}? >

  

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 the class.

Amespace operator, code in the namespace

<?phpnamespace Myproject;use Blah\blah as mine; See "Using namespaces:importing/aliasing" blah\mine (); Calls function Blah\blah\mine () namespace\blah\mine (); Calls function Myproject\blah\mine () Namespace\func (); Calls function Myproject\func () Namespace\sub\func (); Calls function Myproject\sub\func () Namespace\cname::method (); Calls static method "method" of class myproject\cname$a = new Namespace\sub\cname (); Instantiates object of class myproject\sub\cname$b = Namespace\constant; Assigns value of constant myproject\constant to $b?>

  

namespace operator, Global code

<?phpnamespace\func (); Calls function func () Namespace\sub\func (); Calls function Sub\func () Namespace\cname::method (); Calls static method "method" of class cname$a = new Namespace\sub\cname (); Instantiates object of class sub\cname$b = Namespace\constant; Assigns value of constant constant to $b?>

  

Using namespaces: Aliases/imports

The PHP namespace supports two ways to use aliases or imports: Use aliases for class names, or use aliases for namespace names. Note that PHP does not support importing functions or constants.

In PHP, aliases are implemented using the operator use. Here is an example of using all the possible three ways to import:

1. Using the use operator to import/use aliases

<?phpnamespace Foo;use My\full\classname as another;//The following example with use My\full\nsname as Nsname same use my\full\nsname;//import a Global class use \arrayobject; $obj = new Namespace\another; Instantiate Foo\another Object $obj = new Another; Instantiate the My\full\classname object Nsname\subns\func (); Call function my\full\nsname\subns\func$a = new Arrayobject (Array (1)); Instantiate a Arrayobject object//If you do not use \arrayobject, instantiate a Foo\arrayobject object?>

  

2. A row contains multiple use statements

<?phpuse My\full\classname as another, my\full\nsname; $obj = new Another; Instantiate the My\full\classname object Nsname\subns\func (); Call Function my\full\nsname\subns\func?>

  

The import operation is performed in the compilation, but the dynamic class name, function name, or constant name is not.

3. Import and dynamic names

<?phpuse My\full\classname as another, my\full\nsname; $obj = new Another; Instantiate a My\full\classname object $ A = ' another '; $obj = new $a;      A another object is actually?>

  

Additionally, the import operation affects only unqualified names and qualified names. The fully qualified name is not affected by the import because it is deterministic.

4. Import and fully qualified names

<?phpuse My\full\classname as another, my\full\nsname; $obj = new Another; Instantiates object of Class my\full\classname$obj = new \another; Instantiates object of Class another$obj = new Another\thing; Instantiates object of Class my\full\classname\thing$obj = new \another\thing; Instantiates object of Class another\thing?>

  

Using namespaces: Fallback global functions/constants

In a namespace, when PHP encounters an unqualified class, function, or constant name, it uses a different precedence policy to resolve the name. The class name always resolves to the name in the current namespace. Therefore, you must use a fully qualified name when accessing a class name that is inside the system or that is not contained in a namespace, for example:

1. Accessing the global class in the namespace

<?phpnamespace A\b\c;class Exception extends \exception {} $a = new Exception (' Hi '); $a is an object of class a\b\c\exception $b = new \exception (' Hi '); $b is an object of class Exception $c = new Arrayobject; Fatal error, unable to find A\b\c\arrayobject class?>

  

For functions and constants, if the function or constant does not exist in the current namespace, PHP will fallback to use the function or constant in the global space.

2. Reserved global functions/constants in namespaces

<?phpnamespace a\b\c;const e_error = 45;function strlen ($str) {    return \strlen ($STR)-1;} echo E_error, "\ n"; Output "Ini_all" echo, "\ n"; Output "7"-use global constants Ini_allecho strlen (' Hi '), "\ n"; Output "1" if (Is_array (' Hi ')) {//output "is not an array"    echo "is array\n";} else {    echo "was not array\n";}? >

  

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.

Using the Global space description

<?phpnamespace a\b\c;/* This function is A\b\c\fopen */function fopen () {      /* ... */     $f = \fopen (...);//Call global fopen function     return $f;} ?>

  

The Order of namespaces

The most error-prone thing to do since you have a namespace is what the search path for this class is when you use the class.

<?phpnamespace A;use b\d, c\e as f;//function call Foo ();     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 ();        The call is defined in the namespace "a\my" in the function "foo" F ();    First try calling the function "F" defined in Namespace "a"//and then try calling global function "F"//class referencing New B ();    Create an object of class ' B ' defined in namespace ' A '///If not found, attempt to automatically load class "a\b" New D ();    Use an import rule to create an object of class ' D ' defined in namespace ' B '//If not found, attempt to automatically load class "b\d" New F ();   Use an import rule to create an object of class "E" defined in the namespace "C"//If not found, try 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 the static method in another namespace or the namespace function B\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 the class "a\b" D::foo ();   Using the import rule, call the "Foo" Method of Class "D" defined in the 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, attempt to automatically load static method or function A\b::foo () in class "B"//current namespace;  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 the 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 the class "a\b"?>

  

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 () c10>.

  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 () : Parsing of new C ( ): Parsing of new D\e () : In order to refer to the full The global class in the local namespace, you must use the fully qualified name new \c ().

      1. Precede the class name with the current namespace name into:a\b\d\e, and then look for the class.

      2. Attempt to automatically load class a\b\d\e.

      3. Finds the a\b\c class in the current namespace.

      4. Attempt to automatically load class a\b\c.

PHP namespaces

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.

Tags Index: