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 furniture: 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 Page:
<?php
namespace Page;
?>
Note: The namespace declaration must be the very first statement in the PHP file!
Only a declare() statement, like declare(strict_types=1);, may come before it.
The following code is invalid:
<?php
echo "Hello World!";
namespace Page;
...
?>
All classes, interfaces, functions, and constants declared in this PHP file will now belong to the Page namespace:
Example
Create a Table class in the Page namespace:
<?php
namespace Page;
class Table {
public $title = "";
public $rows = 0;
public function info() {
echo "<p>$this->title has $this->rows rows.</p>";
}
}
$table = new \Page\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 Page inside a namespace called Code:
<?php
namespace Code\Page;
?>
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 Page namespace:
<?php
$table = new Page\Table();
$row = new Page\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 Page namespace without the need for the Page\qualifier:
<?php
namespace Page;
$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: