Namespaces address two key issues:
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.
Namespaces are declared at the top of a file using the namespace keyword.
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:
|
Constants, classes, and functions declared in this file will be part of the Html namespace:
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:
Declare a namespace named Html inside another namespace called Code:
| <?php namespace Code\Html; ?> |
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.
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.
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(); ?> |
You can simplify namespace or class names by giving them an alias using the use keyword.
Assign an alias to a namespace using the use keyword:
| <?php use Html as H; $table = new H\Table(); ?> |
Assign an alias to a class using the use keyword:
| <?php use Html\Table as T; $table = new T(); ?> |