Php Namespace
PHP Namespaces were introduced in PHP 5.3 to solve naming conflicts. PHP does not allow two functions or classes to have the same name, as this would result in a fatal error.
PHP Namespaces can solve the following two types of problems:
1. Name conflicts between user-written code and PHP's internal classes/functions/constants or third-party classes/functions/constants.
2. Creating an alias (or shorter name) for very long identifier names (usually defined to alleviate the first problem), improving the readability of the source code.
## Defining Namespaces
By default, all constants, classes, and function names are placed in the global namespace, just as they were before PHP supported namespaces.
Namespaces are declared using the `namespace` keyword. If a file contains a namespace, it must declare the namespace before any other code.
The syntax is as follows:
```php
<?php
// Define code in the 'MyProject' namespace
namespace MyProject;
// ... code ...
You can also define code for different namespaces in the same file, like this:
```php
It is not recommended to use this syntax to define multiple namespaces in a single file. It is recommended to use the curly brace syntax shown below.
```php
To combine global non-namespace code with namespaced code, only the curly brace syntax can be used. The global code must be enclosed in a namespace statement without a name, followed by curly braces, for example:
```php
The only legal code before declaring a namespace is the `declare` statement for defining the source file encoding. All non-PHP code, including whitespace, cannot appear before the namespace declaration.
```php
The following code will cause a syntax error:
<?php
namespace MyProject; // Appearance of "" before the namespace will cause a fatal error - namespace must be the first statement in the script
?>
* * *
## Sub-namespaces
Similar to the relationship between directories and files, PHP namespaces also allow specifying hierarchical namespace names. Therefore, namespace names can be defined in a hierarchical manner:
```php
The example above creates the constant `MyProjectSubLevelCONNECT_OK`, the class `MyProjectSubLevelConnection`, and the function `MyProjectSubLevelConnect`.
* * *
## Using Namespaces
Class names in PHP namespaces can be referenced in three ways:
1. **Unqualified name, or a class name without a prefix,** for example `$a = new foo();` or `foo::staticmethod();`. If the current namespace is `currentnamespace`, `foo` will be resolved as `currentnamespacefoo`. If the code using `foo` is global and not contained in any namespace, `foo` will be resolved as `foo`.
**Warning:** If a function or constant in the namespace is not defined, the unqualified function name or constant name will be resolved as a global function name or constant name.
2. **Qualified name, or a name with a prefix,** for example `$a = new subnamespacefoo();` or `subnamespacefoo::staticmethod();`. If the current namespace is `currentnamespace`, `foo` will be resolved as `currentnamespacesubnamespacefoo`. If the code using `foo` is global and not contained in any namespace, `foo` will be resolved as `subnamespacefoo`.
3. **Fully qualified name, or a name with the global prefix operator,** for example, `$a = new currentnamespacefoo();` or `currentnamespacefoo::staticmethod();`. In this case, `foo` is always resolved as the literal name `currentnamespacefoo` in the code.
Here is an example using all three methods:
**file1.php file code:**
```php
**file2.php file code:**
```php
Note that to access any global class, function, or constant, you can use the fully qualified name, for example `strlen()` or `Exception` or `INI_ALL`.
Accessing global classes, functions, and constants from within a namespace:
```php
* * *
## Namespaces and Dynamic Language Features
The implementation of PHP namespaces is influenced by the dynamic features of the language itself. Therefore, to convert the following code to use namespaces, dynamic element access must be handled.
**example1.php file code:**
```php
You must use the fully qualified name (including the namespace prefix for the class name). Note that because in dynamic class names, function names, or constant names, there is no difference between qualified names and fully qualified names, the leading backslash is unnecessary.
**Dynamic access to namespace elements:**
```php
* * *
## The `namespace` Keyword and `__NAMESPACE__` Constant
PHP supports two abstract ways to access elements within the current namespace: the `__NAMESPACE__` magic constant and the `namespace` keyword.
The value of the `__NAMESPACE__` constant is a string containing the name of the current namespace. In global code, not contained in any namespace, it contains an empty string.
**`__NAMESPACE__` example, code within a namespace:**
```php
**`__NAMESPACE__` example, global code:**
```php
The `__NAMESPACE__` constant is useful when dynamically creating names, for example:
**Using `__NAMESPACE__` to dynamically create names:**
```php
The `namespace` keyword can be used to explicitly access elements in the current namespace or sub-namespaces. It is equivalent to the `self` operator in classes.
**`namespace` operator, code within a namespace:**
```php
**`namespace` operator, global code:**
```php
* * *
## Using Namespaces: Aliasing/Importing
PHP namespaces support two ways to use aliases or importing: using an alias for a class name, or using an alias for a namespace name.
In PHP, aliases are implemented using the `use` operator. Here is an example using all three possible import methods:
**1. Using the `use` operator to import/use aliases:**
```php
**2. Including multiple `use` statements in one line:**
```php
Import operations are performed at compile time, but dynamic class names, function names, or constant names are not.
**3. Importing and dynamic names:**
```php
Additionally, the import operation only affects unqualified names and qualified names. Fully qualified names are definite and are not affected by imports.
**4. Importing and fully qualified names:**
```php
* * *
## Using Namespaces: Fallback Global Functions/Constants
Within a namespace, when PHP encounters an unqualified class, function, or constant name, it uses a different priority strategy to resolve the name. Class names are always resolved to the name in the current namespace. Therefore, when accessing system internal or non-namespaced class names, you must use the fully qualified name, for example:
**1. Accessing global classes within a namespace:**
```php
For functions and constants, if the function or constant does not exist in the current namespace, PHP will fall back to using the function or constant from the global namespace.
**2. Fallback global functions/constants within a namespace:**
```php
* * *
## Global Space
If no namespaces are defined, all class and function definitions are in the global space, just as before PHP introduced the concept of namespaces. Adding the prefix `` before a name indicates that the name is in the global space, even if the name is located in another namespace.
**Using the global space:**
```php
* * *
## Namespace Order
Since the introduction of namespaces, the most error-prone aspect is using classes, specifically the class lookup path.
```php
Name resolution follows these rules:
1. Calls to fully qualified names for functions, classes, and constants are resolved at compile time. For example, `new AB` resolves to class `AB`.
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 `ABC` is imported as `C`, then a call to `CDe()` will be converted to `ABCDe()`.
3. Inside a namespace, all qualified names that are not converted by import rules will have the current namespace name prepended. For example, a call to `CDe()` inside namespace `AB` will be converted to `ABCDe()`.
4. Unqualified class names are converted at compile time according to the current import rules (using the full name instead of the short imported name). For example, if namespace `ABC` is imported as `C`, then `new C()` is converted to `new ABC()`.
5. Inside a namespace (e.g., `AB`), calls to unqualified function names are resolved at runtime. For example, the call to function `foo()` is resolved as follows:
1. Look for a function named `ABfoo()` in the current namespace.
2. Attempt to find and call the function `foo()` in the global space.
6. Inside a namespace (e.g., `AB`), calls to unqualified or qualified class names (non-fully qualified names) are resolved at runtime. Here is the resolution process for `new C()` and `new DE()`:
**Resolution of `new C()`:**
1. Look for class `ABC` in the current namespace.
2. Attempt to autoload class `ABC`.
**Resolution of `new DE()`:**
1. Prepend the current namespace name to the class name to become: `ABDE`, then look for that class.
2. Attempt to autoload class `ABDE`.
To reference a global class in the global namespace, you must use the fully qualified name `new C()`.
YouTip