Namespaces begin with the namespace keyword followed by the namespace name, as shown below:
namespace MyNamespace;
In this way, we can place different classes under different namespaces, improving the organization and maintainability of the code.
Suppose we have a project with the following structure:
- project
- src
- MyNamespace
- MyClass.php
In MyClass.php, we define a class MyClass. To associate this class with the MyNamespace namespace, we need to use the namespace statement at the top of the MyClass.php file, as shown below:
namespace MyNamespace;
class MyClass {
// class implementation
}
With this, the MyClass class is now part of the MyNamespace namespace.
In other PHP files, we can use the use statement to import the namespace and access the class:
use MyNamespace\MyClass;
$object = new MyClass();
Suppose our project directory structure is as follows:
- project
- src
- MyNamespace
- MyClass.php
- SubNamespace
- MySubClass.php
In MyClass.php, we define the MyClass class under the MyNamespace namespace; in MySubClass.php, we define the MySubClass class under the MyNamespace\SubNamespace namespace.
In other PHP files, we can import both classes using the following:
use MyNamespace\MyClass;
use MyNamespace\SubNamespace\MySubClass;
$myClass = new MyClass();
$mySubClass = new MySubClass();
In this way, we can clearly see the hierarchical relationship between the classes in the PHP code, and we can also accurately find the corresponding files in the file system.
Using namespaces properly helps structure your code more clearly, reducing confusion in development. By organizing related classes and modules into appropriate namespaces, we not only improve code quality but also help development teams collaborate more effectively.
Project structure:
- project
- src
- MyNamespace
- MyClass.php
- SubNamespace
- MySubClass.php
- index.php
Contents of MyClass.php:
<?php
namespace MyNamespace;
class MyClass {
public function sayHello() {
echo "Hello from MyClass!";
}
}
Contents of MySubClass.php:
<?php
namespace MyNamespace\SubNamespace;
class MySubClass {
public function sayHello() {
echo "Hello from MySubClass!";
}
}
Contents of index.php:
<?php
require_once 'src/MyNamespace/MyClass.php';
require_once 'src/MyNamespace/SubNamespace/MySubClass.php';
use MyNamespace\MyClass;
use MyNamespace\SubNamespace\MySubClass;
$myClass = new MyClass();
$myClass->sayHello();
$mySubClass = new MySubClass();
$mySubClass->sayHello();
When running the index.php file, the output will be as follows:
Hello from MyClass!
Hello from MySubClass!