Skip to main content

PHP OOP Namespaces

By SamK
0
0 recommends
Category(s)
Topic(s)

Namespaces serve as qualifiers that enhance organization by grouping related classes that collaborate to accomplish a task. They also allow multiple classes to share the same name without conflicts.

For instance, consider a group of classes representing a car, such as Car, Engine, and Wheel, and another group representing a train, like Length, Engine, and Track. By using namespaces, you can organize these classes into separate groups, ensuring that identical class names, such as Engine, are distinguished and don’t conflict.

Declaring a Namespace

Syntax: Namespaces are defined at the start of a PHP file using the namespace keyword. This is must.

Example:

<?php
namespace Vehicle;
echo "Welcome to WebmasterMaze";
...
?>

Using Namespaces

Constants, classes, and functions defined in the namespace file become a part of that namespace. 

Any code that follows a namespace declaration operates within that namespace, allowing classes to be instantiated without any additional qualifiers. 

Example:

<?php
namespace Vehicle;
?>
<!DOCTYPE html>
<html>
<body>

<?php
// Defining a class within the Vehicle namespace
class Car {
    public $make;
    public $model;

    public function __construct($make, $model) {
        $this->make = $make;
        $this->model = $model;
    }
}

// Defining a constant
const VEHICLE_TYPE = 'Car';

// Defining a function
function getVehicleType() {
    return VEHICLE_TYPE;
}

$myCar = new Car('Toyota', 'Corolla');  // Create an instance of the Car class
echo $myCar->make . "<br>";  // Output: Toyota
echo $myCar->model . "<br>";  // Output: Corolla

echo getVehicleType();  // Output: Car
echo "<br>";  // New line for clarity

// Output the constant value
echo VEHICLE_TYPE;  // Output: Car
?> 
</body>
</html>

To access classes from outside the namespace, the namespace must be prefixed to the class.

Example: Suppose if a vehicle namespace has two classes Car and Bike, then the code to utilize those classes will be: 

$car = new Vehicle\Car();
$bike = new Vehicle\Bike();

When multiple classes from the same namespace are used simultaneously, it is more convenient to use the namespace keyword, as shown below:

<?php
namespace Vehicle;
$car = new Car(); // No need to use Vehicle\
$bike = new Bike();
?>

Nested Namespaces

For better organization, nested namespaces can be used.

Example: Declare a namespace named  Vehicle within a namespace called Transport.

<?php
namespace Transport\Vehicle;
?>

Namespace Alias

Giving a namespace or class an alias can simplify code writing. This can be achieved using the use keyword.

Example:

<?php
// Use aliasing for Vehicle\Car and Vehicle\Bike
use Vehicle\Car as C;
use Vehicle\Bike as B;

// Create instances using the aliases
$car = new C("Toyota", "Corolla");
$bike = new B("Honda", "CBR");
?>

Questions & Answers