PHP Namespaces

PHP Namespaces

As your PHP projects grow, or as you start using third-party libraries (like packages from Composer), you run into a serious problem: Name Collisions.

If you create a class named Table (representing an HTML table), and you download a database library that also has a class named Table (representing a database table), PHP will crash with a "Cannot redeclare class" error.

Namespaces solve this by grouping related classes, functions, and constants together under a unique umbrella name.


Declaring a Namespace

Namespaces are declared at the very beginning of a file using the namespace keyword. It must be the very first statement in your file (before any HTML or other PHP code).

<?php
namespace Html;

class Table { public $title = ""; public $numRows = 0; } ?>

Now, this is no longer just the Table class; its full name is Html\Table.


Accessing Classes in Namespaces

When you want to use a class from a different namespace, you can either provide its fully qualified name, or you can "import" it into your current file using the use keyword.

<?php
// Using the fully qualified name
$table = new Html\Table();

// OR importing it at the top of the file use Html\Table; $table = new Table(); ?>

Giving Aliases (As)

If you import two classes with the exact same name from different namespaces, you can give them an alias to prevent collisions using as:

use Database\Table as DbTable; use Html\Table as HtmlTable;