Namespaces are used to resolve a conflict between the user-written code and the name of a class/function/constant or third-party class/function/constant within PHP. Create an alias (or short) name for a long identifier name to improve the readability of the source code.
Although any valid PHP code can be included in a namespace, only the following types of code are affected by namespaces: classes (including abstract classes and traits), interfaces, functions, and constants.
If a file contains a namespace, it must declare the namespace before all other code, except one: thedeclare keyword, which defines the declare statement for how the source file is encoded. The code includes whitespace characters that do not appear before the declaration of the namespace.
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.
Defining child namespaces
<?phpnamespace myproject\sub\level;const CONNECT_OK = 1;class Connection {/* ... */}function CONNECT () {/* ... */}
Define multiple namespaces in the same file
<?phpnamespace myproject;const CONNECT_OK = 1;class Connection {/* ... */}function CONNECT () {/* ... */ }namespa Ce anotherproject;const CONNECT_OK = 1;class Connection {/* ... */}function CONNECT () {/* ... */ }
It is not recommended to use this syntax to define multiple namespaces in a single file. It is recommended that you use the following form of curly braces syntax.
<?phpnamespace MyProject {Const CONNECT_OK = 1;class Connection {/* ... */}function CONNECT () {/* ... */ }}names Pace Anotherproject {Const CONNECT_OK = 1;class Connection {/* * ... */}function CONNECT () {/* ... */ }}
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.
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.
A class can be referenced in 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 will be parsed 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.
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.
A fully qualified name, or a name that contains 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\fooin 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.
Note: The relative path to the file that is contained in the parent file is for the parent file directory, not the sub-file directory.
PHP supports two abstract methods for accessing elements inside the current namespace, __NAMESPACE__
Magic constants, and namespace keywords.
__NAMESPACE__
can represent strings, and others are the same as NAMESAPCE.
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;//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
Importing/using aliases with the use operator, with multiple usage statements in a row
<?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
Import and dynamic names
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; To actually another an object
Import and fully qualified names
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
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;}
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 the name of a class that is inside the system or that is not included in the namespace. 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;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, A\b\c\arrayobject class not found
<?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";}
Name resolution follows these rules:
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.
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 ().
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 ().
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 ().
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:
Look for a function named A\b\foo () in the current namespace
Try to find and invoke the function foo () in global space.
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 ():
Parsing of New D\e ():
In order to refer to global classes in the global namespace, you must use the fully qualified name new \c ().
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.
Finds the A\b\c class in the current namespace.
Attempt to automatically load class a\b\c.
<?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"?>