PHP namespace

PHP namespace (namespace) was added in PHP 5.3. If you have studied C# and Java, namespace is nothing new. However, it still has a very important significance in PHP.

PHP namespace can solve the following two types of problems:

Between user-written code and PHP internal classes/functions/constants or third-party classes/functions/constants name conflict.

Create an alias (or short) name for a very long identifier name (usually defined to alleviate the first type of problem) to improve the readability of the source code.

Define namespace

By default, all constant, class and function names are placed in the global space, just like before PHP supported namespaces.

In naming the space, we usually use the name or abbreviation of the company, enterprise, or individual as the identifier. The first letter must be capitalized and cannot start with a number.

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


// The code is defined in the 'MyProject' namespace
namespace MyProject;
// ... code. ..

?>

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


namespace MyProject1;
// PHP code in the MyProject1 namespace

namespace MyProject2;
// PHP code in the MyProject2 namespace

// Another syntax

namespace MyProject3 {
// PHP code in the MyProject3 namespace

}

?>

The only legal code before declaring a namespace is the declare statement that defines the encoding of the source file. All non-PHP code, including whitespace, must not appear before a namespace declaration.

The following code will cause a syntax error:



namespace MyProject; // "< appears before the namespace html>" will cause a fatal error - the namespace must be the first statement of the program script
?>

Subnamespace

The declaration of the subnamespace is exactly the same as the previous example . The only difference is that we add a \ symbol to separate the namespace and the subnamespace. The subnamespace can be divided into any level, as long as it can be clearly divided by function:


namespace MyProject\Sub\Level; //Declare a hierarchical single namespace

const CONNECT_OK = 1;
class Connection { /* ... */ }
function Connect() { /* ... */ }
}

?>

The above example creates the constant MyProject\Sub\Level\CONNECT_OK, class MyProject\ Sub\Level\Connection and function MyProject\Sub\Level\Connect.

Namespace usage

Class names in PHP namespaces can be referenced in three ways:

Unqualified name, or class name without prefix, such as $a=new foo(); or foo::staticmethod();. If the current namespace is currentnamespace, foo will be resolved to currentnamespace\foo. If the code using foo is global and does not contain code in any namespace, foo will be resolved as foo. Warning: If a function or constant in the namespace is undefined, the unqualified function or constant name is resolved to a global function or constant name.

Qualified name, or name containing a prefix, such as $a = new subnamespace\foo(); or subnamespace\foo::staticmethod();. If the current namespace is currentnamespace, foo will be resolved to currentnamespace\subnamespace\foo. If the code using foo is global, code not contained in any namespace, foo will be resolved to subnamespace\foo.

Fully qualified name, or a name that includes a global prefix operator, for example, $a = new \currentnamespace\foo(); or \currentnamespace\foo::staticmethod();. In this case, foo is always resolved to the literal name currentnamespace\foo in the code.

The following is an example of using these three methods:

file1.php file code

file2.php file code

Be careful to access any Global classes, functions, or constants can use fully qualified names, such as \strlen() or \Exception or \INI_ALL.

Accessing global classes, functions and constants within a namespace:

Namespace and dynamic language features

The implementation of PHP namespaces is subject to its The influence of the dynamic characteristics of language itself. So if you want to convert the code below into a namespace, access the elements dynamically.

example1.php file code:

Must use a fully qualified name (class name including namespace prefix). Note that the leading backslash is unnecessary because there is no difference between qualified and fully qualified names in dynamic class names, function names, or constant names.

Dynamic access to namespace elements

namespace keyword and __NAMESPACE__ constant

PHP supports two abstractions for accessing the current namespace internals Element methods, __NAMESPACE__ magic constant and namespace keyword.

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

__NAMESPACE__ Example, code in namespace


namespace MyProject;

echo '"' , __NAMESPACE__, '"'; // Output "MyProject"

?>

##__NAMESPACE__ example, global code


echo '"', __NAMESPACE__, '"'; // Output ""

?>

The constant __NAMESPACE__ is useful when creating names dynamically, for example:

Use __NAMESPACE__ to dynamically create names


namespace 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 sub-namespace. It is equivalent to the self operator in classes.

namespace operator, code in the namespace

namespace operator, global code

Use namespace: alias/import

PHP namespace supports two ways of using aliases or imports: using aliases for class names, or using aliases for namespace names. Note that PHP does not support imported functions or constants.

In PHP, aliases are implemented through the operator use. The following is an example of using all three possible import methods:

1. Use the use operator to import/use aliases

2. One line contains multiple use statements

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

3. Import and dynamic names

In addition, the import operation only affects unqualified names and qualified names. Fully qualified names are not affected by imports because they are deterministic.

4. Import and fully qualified name

use Keyword usage:

must be at the top of the PHP file, that is, the opening tag of PHP

When using the use keyword to import code, there is no need to add the \ symbol at the beginning of the class name, because PHP assumes that the imported namespace is fully qualified.

The use keyword must be used in the global scope (that is, it cannot be used in a class or function)

The use keyword can be placed under the declaration of the namespace, using to import code in other namespaces.

Using namespaces: fallback global functions/constants

In a namespace, when PHP encounters an unqualified class, function, or constant name, it Use a different precedence strategy to resolve the name. Class names always resolve to names in the current namespace. Therefore, when accessing class names inside the system or not included in the namespace, you must use fully qualified names, for example:

1. Access global classes in the namespace

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

2. Backup global functions/constants in the namespace

Global space

If no namespace is defined, all classes and functions are defined globally space, as it was before PHP introduced the concept of namespaces. Prefixing a name with \ indicates that the name is in the global space, even if the name is in another namespace.

Instructions for using global space

To use the global name space, you only need to add a \ symbol before the class name. For example: throw new \ Exception();

The order of the namespace

Since the namespace was created, the most error-prone thing is when using a class, what is the search path for this class.


namespace A;
use B\D, C\E as F;

// Function call

foo (); // First try to call the function foo() defined in the namespace "A"
// Then try to call the global function "foo"

\foo(); // Call the global space Function "foo"

my\foo(); // Call function "foo" defined in namespace "A\my"

F(); // First try to call function defined in Function "F" in namespace "A"

// Try calling global function "F" again

// Class reference

new B(); // Create an object of class "B" defined in namespace "A"
// If not found, try to autoload class "A\B"

new D(); // Use import Rule, create an object of class "D" defined in namespace "B"
// If not found, try to automatically load class "B\D"

new F(); // Using import rules, create an object of class "E" defined in namespace "C"
// If not found, try to autoload class "C\E"

new \B() ; // Create an object of class "B" defined in the global space
// If not found, try to automatically load class "B"

new \D(); // Create definition An object of class "D" in the global space
// If not found, try to automatically load class "D"

new \F(); // Create an object defined in the global space An object of class "F"
// If not found, try to autoload class "F"

// Call a static method or namespace function in another namespace

B\foo(); // Call the function "foo" in the namespace "A\B"

B::foo(); // Call the class "B" defined in the namespace "A" "foo" method
// If class "A\B" is not found, try to automatically load class "A\B"

D::foo(); // Use import rules to call "foo" method of class "D" defined in namespace "B"
// If 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 the class "B" in the global space
// If class "B" is not found, try to automatically load class "B"

// Static method or function in the current namespace

A\B::foo( ); // Call the "foo" method of class "B" defined in namespace "A\A"
// If 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 namespace "A\B"
// If class "A\B" is not found, try to automatically Loading class "A\B"

?>

Name resolution follows the following rules:

1. For fully qualified names of functions, classes and constants Calls are resolved at compile time. For example new \A\B resolves to class A\B.

2. All unqualified names and qualified names (non-fully qualified names) are converted at compile time according to the current import rules. For example, if namespace A\B\C is imported as C, then calls to C\D\e() will be translated to A\B\C\D\e().

3. Within the namespace, all qualified names that are not converted according to the import rules will have the current namespace name in front of them. For example, if C\D\e() is called within namespace A\B, C\D\e() will be converted to A\B\C\D\e().

4. Unqualified class names are converted at compile time according to the current import rules (full names are used instead of short import names). For example, if namespace A\B\C is imported as C, then new C() is converted to new A\B\C() .

5. Within a namespace (such as A\B), function calls to unqualified names are resolved at runtime. For example, a call to function foo() is parsed like this:

Find a function named A\B\foo() in the current namespace

Try to find and call global Function foo() in space.

6. Calls to unqualified names or qualified name classes (non-fully qualified names) within a namespace (such as A\B) are resolved at runtime. The following is the parsing process of calling new C() and new D\E(): Parsing of new C(): Parsing of new D\E(): In order to refer to the global class in the global namespace, the fully qualified name new must be used \C().

Add the current namespace name in front of the class name to become: A\B\D\E, and then search for the class.

Try to automatically load class A\B\D\E.

Find classes A\B\C in the current namespace.

Try to automatically load class A\B\C.



Continuing Learning
||
submit Reset Code
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!