PHP Namespaces
PHP Namespaces
PHP namespaces are used to prevent naming conflicts between classes, interfaces, functions, and constants.
Namespaces are used to group related code together under a name - to avoid naming conflicts when your code grows, or when you use code from multiple sources.
Why Use Namespaces?
- To avoid name conflicts, especially in larger projects
- To organize code into logical groups
- To separate your code from code in libraries
- To allow the same name to be used for more than one class, without conflict
Assume you have a set of classes which describe an HTML table: Table, Row and Cell. In addition you have another set of classes which describe furnitures: Table, Chair and Bed. Here, namespaces can be used to organize these classes into two different groups, which prevents the two Table classes from being mixed up.
Declaring a Namespace
Namespaces must be declared at the beginning of a PHP file, using the
namespace keyword, followed by a name
for the namespace.
Here, we declare a namespace called Html:
<?php
namespace Html;
?>
Note: The namespace declaration must be the very first thing in the PHP file! The following code is invalid:
<?php
echo "Hello World!";
namespace Html;
...
?>
All classes, interfaces, functions, and constants declared in this PHP file will now belong to the Html namespace:
Example
Create a Table class in the Html namespace:
<?php
namespace Html;
class Table {
public $title = "";
public $rows = 0;
public function info() {
echo "<p>$this->title has $this->rows rows.</p>";
}
}
$table = new \Html\Table();
$table->title = "My table";
$table->rows = 5;
?>
<!DOCTYPE
html>
<html>
<body>
<?php
$table->info();
?>
</body>
</html>
Try it Yourself »
For further organization, it is possible to have nested namespaces:
Syntax
Declare a namespace called Html inside a namespace called Code:
<?php
namespace Code\Html;
?>
Using Namespaces
Any code that follows a namespace declaration is operating inside the namespace, so classes that belong to the namespace can be instantiated without any qualifiers. To access classes from outside a namespace, the class needs to have the namespace attached to it.
Example
Use classes from the Html namespace:
<?php
$table = new Html\Table();
$row = new Html\Row();
?>
Try it Yourself »
When many classes from the same namespace are being used at the same time, it is
easier to use the namespace keyword:
Example
Use classes from the Html namespace without the need for the Html\qualifier:
<?php
namespace Html;
$table = new Table();
$row = new Row();
?>
Try it Yourself »
Namespace Alias
It can be useful to give a namespace or class an alias to make it easier to write. This is
done with the use keyword: