A namespace is a declarative region that holds a set of definitions under specified namespace for classes, functions, constants, etc. It is used to prevent naming conflicts across multiple PHP scripts, Especially working with large scale projects or including external libraries.
- Use of Namespace
- Global Namespace
- Declaration of Namespace
- Implementation of Namespace
- Namespace Alias
- Key Points
- Avoid Naming Conflicts: It prevents name clashes among identifiers with same name.
- Organize Code: It groups classes and functions into logical namespace.
- Improve Code Readability: It makes, the code organized and easier to understand.
If a class or function is not declared within a namespace, By default, it belongs to the global namespace.
Namespace for PHP script can be declared using the keyword namespace
.
Example:
namespace MyProject\MyNamespace;
class MyClass {
// ...
}
function myFunction() {
// ...
}
If a class or function is declared within a namespace, It can not be accessed from global namespace. To use a class and function from a particular namespace, It can be implemented by either use the fully qualified name or import using the use
keyword.
Example:
// Fully qualified name:
\MyProject\MyNamespace\MyClass::myStaticMethod();
$obj = new \MyProject\MyNamespace\MyClass();
$obj->myMethod();
// Using the `use` keyword:
use MyProject\MyNamespace\MyClass;
$obj = new MyClass();
$obj->myMethod();
To shorten the fully qualified name of namespace, by create an aliases for namespace with the as
keyword.
use MyProject\MyNamespace as MPN;
$obj = new MPN\MyClass();
- Provide meaningful names for namespace declaration that reflect the project structure.
- Avoid too many nested namespace.
- Import namespaces with
use
keyword to improve code readability. - Use a PSR-4 autoloader to automatically load classes based on their namespaces.