PHP Name Spaces

PHP Name Spaces


PHP Namespaces provide a way in which to group related classes,interfaces,functions and constants.Namespaces are way of encapsulating items.

A namspace is like a folder or directory.

In the PHP world namespaces are designed to solve two problems that authors of libraries and applications encounter when creating resusable code elements such as classes or functions:

  • Name collisions between code you create,and internal PHP classes/functions/constants or third-party classes/functions/constants.
  • Ability to alias (or shorten )Extra_Long_Names designed to alleviate the first problem,improving readability of source code.

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

Syntax of Namespace:

Declare a namespace called Html:

             namespace Html;

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

                           <?php

                     echo "Hello World!";
                 namespace Html;
           
 ?>

For Example : 

Create a Table class in the using Html namespace:

Output : Table 'My table' has 5 rows.

we can declare that we're in one of the namespaces and then we can just call that namespace's

Normally, a backslash will be used in PHP as a namespace separator.

             namespace Code\Html;    (a namespace called Html inside a namespace called Code)

 

Here is another example of using Namespace :

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.

we have two files( Html.php) and (Index.php)

when we executed Index.php file then output is : Table 'My table' has 5 rows.

                                                                                 The row has 3 cells.

It can be useful to give a namespace or class an alias to make it easier to write.

for Example :

    use Html as H;
    $table = new H\Table();