Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

Learn PHP Namespaces



PHP Namespaces

Namespaces are one of the most powerful features of PHP
Namespaces are
used to avoid name collisions between classes with the same name placed in different
directories or different
Namespaces are used to organize the code into logical groups and
to avoid name collisions
Namespaces are declared at the beginning of a file.
A namespace declaration starts with the namespace keyword followed by the namespace name
and ends with the closing tag
A namespace name must start with a letter or underscore





Declaring a Namespace

Namespaces are declared at the beginning of a file using the namespace keyword:


Syntax

<?php
namespace Html;
?>


Note: A namespace declaration must be the first thing in the PHP file. The following code would be invalid:


<?php
echo "Hello World!";
namespace Html;
...
?>


Constants, classes and functions declared in this file will belong to the Html namespace:


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>

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();
?>


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();
?>



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:


Example

Give a namespace an alias:

<?php
use Html as H;
$table = new H\Table();
?>


Example

Give a class an alias:

<?php
use Html\Table as T;
$table = new T();
?


Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java