Namespaces allow for better organization by grouping classes that work together to perform a task.
They allow the same name to be used for more than one class
Namespaces are declared at the beginning of a file using the namespace keyword:
File Name :
namespace Ittutorial;
Example
File Name :
<?php
namespace Ittutorial;
class Myclass{
public $title = "";
public $numRows = 0;
public function message() {
echo "<p>Table '{$this->title}' has {$this->numRows} rows.</p>";
}
}
$obj = new Myclass();
$obj->title = "My table";
$obj->numRows = 5;
?>
<!DOCTYPE html>
<html>
<body>
<?php
$obj->message();
?>
</body>
</html>
Declare a namespace called ittutorial inside a namespace called Code:
File Name :
namespace Code\Ittutorial;
Html.php
File Name :
<?php
namespace Html;
class Table {
public $title = "";
public $numRows = 0;
public function message() {
echo "<p>Table '{$this->title}' has {$this->numRows} rows.</p>";
}
}
class Row {
public $numCells = 0;
public function message() {
echo "<p>The row has {$this->numCells} cells.</p>";
}
}
?>
index.php
File Name :
<?php
include "Html.php";
$table = new Html\Table();
$table->title = "My table";
$table->numRows = 5;