This site is mobile accessible. Press the "Tap Here" button to use a different font-size.
Smartphone icons created by Freepik - Flaticon
Namespaces are declared at the beginning of a file using the namespace keyword:
Declare a namespace called Html:
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:
Create a Table class in 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 further organization, it is possible to have nested namespaces:
namespace Code\Html;
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.
Use classes from the Html namespace:
$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
keyword:Use classes from the Html namespace without the need for the Html\qualifier:
namespace Html; $table = new Table(); $row = new Row();
It can be useful to give a namespace or class an alias to make it easier to write. This is done with the
keyword:Give a namespace an alias:
use Html as H; $table = new H\Table();
Give a class an alias:
Give a class an alias:
use Html\Table as T; $table = new T();
Eventually the navigation links, above, will be replaced by these (previous) and (next) buttons below.
Animated PHP icons used in the buttons provided by ICONS8.COM. Smartphone icons created by Freepik - Flaticon
Module 6 quiz