Welcome to another tutorial; here, you will learn the basics of PHP Namespaces.
Firstly, let's understand what PHP Namespaces are:
PHP Namespaces are a way to resolve the name collision problem. PHP Namespaces are used for encapsulating items to reuse the same names without name conflicts.
PHP Namespaces are qualifiers that are used for solving two different problems:
For example, you have two different sets of classes. One set of classes describes an HTML table like Table, Row, and Cell, and the second set of classes for describing furniture like Chair, Table, and Bed. You can use namespaces to organize the classes into two different groups and at the same time prevent two classes, Table and Table, from mixing up.
You can declare Namespaces at the beginning of a file by using the namespace keyword.
namespace Html;
Example:
<?php
namespace Html;
class Table {
public $title = "";
public $numRows = 0;
public function message() {
echo "<p>Table '{$this->title}' has {$this->numRows} rows.</p>";
}
}
$table = new Table();
$table->title = "My table";
$table->numRows = 5;
?>
<!DOCTYPE html>
<html>
<body>
<?php
$table->message();
?>
</body>
</html>
A code following namespace declaration operates inside the namespace, so classes belonging to the namespace can be instantiated without any qualifiers. However, for accessing classes from outside a namespace, the classes require to have the namespace attached to them.
$table = new HtmlTable()
$row = new HtmlRow();
When using many classes from the namespace simultaneously, it is easier to use the namespace keyword.
namespace Html;
$table = new Table();
$row = new Row();
It is helpful to give a namespace or class an alias to make writing it easy. You can do this by using a keyword.
use Html as H;
$table = new HTable();