Note 008 PHP Namespaces-Medium

Source: Internet
Author: User

Using Namespaces: Basics

PHP determines which namespace to use for element hair methods

Here, you can make a simple analogy between the PHP namespace and the file system. There are three ways to access a file in the file system:

Relative file name forms such as Foo.txt. It will be parsed to Currentdirectory/foo.txt, where CurrentDirectory represents the current directory. So if the current directory is/home/foo, the file name is parsed to/home/foo/foo.txt.

Relative pathname forms such as subdirectory/foo.txt. It will be parsed into currentdirectory/subdirectory/foo.txt.

Absolute pathname forms such as/main/foo.txt. It will be parsed into/main/foo.txt.

The PHP namespace uses the same principle. For example, the class name can be referenced normally in the following three ways:

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.

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.

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.

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

Key to namespaces in dynamic classes

example1.php

<?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?>

If you want to convert the following code into a namespace, 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.

<?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; Output classname::__construct$b = ' funcname '; $b (); Output Funcnameecho constant (' constname '), "\ n"; Output global/* Note: If you use double quotes, you must take the form of "\\namespacename\\classname", which is because of the reason for the string escaping, please refer to PHP escape */$a = ' \namespacename\ ClassName '; $obj = new $a; Output namespacename\classname::__construct$a = ' Namespacename\classname '; $obj = new $a; Still output namespacename\classname::__construct$b = ' namespacename\funcname '; $b (); Output namespacename\funcname$b = ' \namespacename\funcname '; $b (); Still output Namespacename\funcnameecho constant (' \namespacename\constname '), "\ n"; Output Namespacedecho constant (' namespacename\constname '), "\ n"; Still output 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. Note: The magic constant is two underscores

NAMESPACE

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;echo ' "', __namespace__, '"; Output "MyProject"?>

The global code, that is, when there is no namespace, outputs an empty string.

Constant NAMESPACE is useful when creating names dynamically, for example:

<?phpnamespace myproject;function Get ($classname) {    $a = __namespace__. '\\' . $classname;    return new $a;}? >

Namespace

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.

<?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?>

Using aliases/imports in namespaces

Allowing the external fully qualified name to be referenced or imported through an alias 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 import methods: Use aliases for class names, use aliases for interfaces, or use aliases for namespace names. PHP 5.6 starts by allowing you to import functions or constants or set aliases for them.

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

<?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;//importing a function (PHP 5.6+) use function my\full\functionname;//aliasing a function (PHP 5.6+) US e function My\full\functionname as func;//importing a constant (PHP 5.6+) use const my\full\constant; $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 Arrayobject object//If use \arrayobject is not used, instantiate a Foo\arrayobject object func (); Calls function My\full\functionnameecho CONSTANT; Echoes the value of my\full\constant?>

Note A leading backslash is unnecessary and not recommended for names in namespaces that contain the fully qualified name of the namespace delimiter, such as Foo\bar, and the relative global name that does not contain the namespace delimiter, because the imported name must be fully qualified, Relative parsing is not based on the current namespace.

To simplify operations, PHP also supports using multiple use statements on a single line.

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

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

<?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?>

Resolve Priority Policy

In a namespace, when PHP encounters an unqualified class, function, or constant name, it uses a different precedence policy to resolve the name.

The resolution priority of the class

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:

<?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?>

Resolution precedence for functions and constants

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.

<?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";}? >

The above is the Note 008 PHP namespace-medium content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

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