Mitul Dabhi
answered Apr 25 '23 00:00
In PHP, namespaces are a way to prevent naming conflicts between classes, functions, and constants with the same name defined in different parts of a project or in different third-party libraries.
To define a namespace in PHP, the namespace keyword is used, followed by the desired namespace name. For example:
n
amespace MyNamespace;
class MyClass {
// class code here
}
To use a class, function, or constant from another namespace, the use keyword is used to specify the namespace. Here's an example:
use AnotherNamespace\AnotherClass;
$object = new AnotherClass();
An alias can also be used to simplify the namespace reference. For instance:
use AnotherNamespace as AN;
$object = new AN\AnotherClass();
When using a namespace, PHP looks for the class, function, or constant in the current namespace first. If it's not found, PHP will look for it in the global namespace.
Namespaces can be nested using the backslash () character. For example:
namespace MyNamespace\SubNamespace;
class MyClass {
// class code here
}
In this example, MyClass is part of the SubNamespace namespace, which is a sub-namespace of MyNamespace .