What is namespaces?

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;

$row = new Html\Row();
$row->numCells = 3;
?>

<html>
<body>

<?php $table->message(); ?>
<?php $row->message(); ?>

</body>
</html>

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:

File Name :

<?php
include "Html.php";
use Html as H;
$table = new H\Table();
$table->title = "My table";
$table->numRows = 5;
?>

<html>
<body>

<?php $table->message(); ?>

</body>
</html>





Previous Next


Trending Tutorials




Review & Rating

0.0 / 5

0 Review

5
(0)

4
(0)

3
(0)

2
(0)

1
(0)

Write Review Here