PHP - Custom Type Namespaces

Introduction

PHP use namespaces to organize classes.

It is like you use folder to organize files.

Class with the same name can be stored in different folders.

Specifying a namespace has to be the first thing in a file.

Use the namespace keyword followed by the namespace.

Each section of the namespace is separated by \

If you do not specify the namespace, the class will belong to the base namespace, or root.

At the beginning of both files Book.php and Customer.php, add the following:

<?php 

namespace Bookstore\Domain; 

The preceding line of code sets the namespace of our classes as Bookstore\Domain.

The full name of our classes then is Bookstore\Domain\Book and Bookstore\Domain\Customer.

You can specify the full name of the classes when referencing them, that is, using


$customer = new Bookstore\Domain\Book(); 

instead of $book = new Book();

Or you can use the keyword use to specify a full class name at the beginning of the file, and then use the simple name of the class in the rest of that file.

<?php 
     use Bookstore\Domain\Book; 
     use Bookstore\Domain\Customer; 

     require_once __DIR__ . '/Book.php'; 
     require_once __DIR__ . '/Customer.php'; 
     //... 

     $customer1 = new Customer(1, 'John', 'Doe', 'a@mail.com'); 
     $customer2 = new Customer(2, 'Mary', 'Smith', 'mp@mail.com'); 

Here, each time that we reference Book or Customer, PHP will know that we actually want to use the full class name.

To reference the classes with identical names, use

  • the full class name-with namespace
  • alias

Alias

Imagine that we have two Book classes, the first one in the namespace Bookstore\Domain and the second one in Library\Domain.

To solve the conflict, you could do as follows:

use Bookstore\Domain\Book; 
use Library\Domain\Book as LibraryBook; 

whenever you reference the class LibraryBook, you will actually be referencing the class Library\Domain\Book.

Related Topics