Curriculum
Course: PHP Basic
Login

Curriculum

PHP Basic

PHP Install

0/1

PHP Casting

0/1

PHP Constants

0/1

PHP Magic Constants

0/1

PHP Operators

0/1

PHP Reference

0/276
Text lesson

PHP Namespaces

PHP Namespaces

Namespaces address two key issues:

  1. Organization: They help group related classes together, improving code structure.
  2. Name Conflicts: They allow the use of the same class name in different contexts without causing conflicts.

For example, you might have a Table, Row, and Cell class for HTML tables, and another Table, Chair, and Bed class for furniture. Namespaces can separate these groups, avoiding confusion between the Table classes in each context.

Declaring a Namespace

Namespaces are declared at the top of a file using the namespace keyword.

Syntax

Declare a namespace named Html using the following syntax:

<?php
namespace Html;
?>

Note: The namespace declaration must be the very first line 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 be part of the Html namespace:

Example

Define a Table class within the Html namespace:

<?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 better organization, you can use nested namespaces:

Syntax

Declare a namespace named Html inside another namespace called Code:

<?php
namespace Code\Html;
?>

Using Namespaces

Any code following a namespace declaration operates within that namespace, so classes can be instantiated without qualifiers. To access classes from outside the namespace, you need to specify the full namespace.

Example

To use classes from the Html namespace, you need to specify the namespace when instantiating the class

<?php
$table = new Html\Table();
$row = new Html\Row();
?>

When multiple classes from the same namespace are being used, it’s simpler to import the entire namespace with the use keyword.

Example

To use classes from the Html namespace without needing the Html\ qualifier, you can import the namespace with the use keyword.

<?php
namespace Html;
$table = new Table();
$row = new Row();
?>

Namespace Alias

You can simplify namespace or class names by giving them an alias using the use keyword.

Example

Assign an alias to a namespace using the use keyword:

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

Example

Assign an alias to a class using the use keyword:

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