why we use namespace in php

 

 

 

 

 

 

 

 

Why we need namespace in php; As php classes getter longer and longer or any third party libraries when exported to file , our php file may accidently get collapsed with other classes or functions or so more .So here comes namespace in php which was introduced in php 5.3.

Otherwise we have to give full names to our classes ,functions, table prefixes that would be going to be long and heavy procedure. Like  as follows.

why we use namespace in php

Symfony_monolog_class_private_methods_joins_data_fixtures  ; this line shows that long extra coding needed every time whenever we need that class etc.

Namespace comes  to our rescue!we can declare the same function, class,constant definitions and interfacein separate namespaces .

 Essentialy, a namespace is nothing more than a hierarchically labeled code block holding regular PHP code.

This way we avoid our php code from collapsing and fatal errors.

 

In short, PHP constants, classes, and functions can be grouped into namespaced libraries.

How  to use or define namespace

when used no white space or php preceding code is needed otherwise namespace would work.

<?php
// define this code in theSymfonyProject namespace
namespace SymfonyProject;

 

PHP uses the backslash as its namespace separator.

There are three types of code which we can call from namespace.

Unqualified Name

Qualified Name

Fully Qualified Name

Description:

Unqualified Name

// Unqualified name, resolves to the namespace you are currently in (SymfonyProject\MyClass)

<?php
namespace SymfonyProject;

class MyClass {
static function static_method()
{
echo ‘Hello, symfony!’;
}
}

MyClass:static_method();

Qualified Name

Description:

It is used with blackslash with namespace like

<?php
namespace SymfonyProject\Database;

require ‘symfonyproject/Videoup/input.php’;

$input = new SymfonyProject\Videoup\Input();

Fully Qualified namespace

When we require total absolute path to our class ,funciton, interface or definition.

Now see the example below ; only difference of syntax as follows :

<?php
namespace SymfonyProject\Database;

require ‘Symfonyproject/Videoup/input.php’;

$input = new \SymfonyProject\Videoup\Input();

 

 We can alias to it a different name alternatively,

<?php
namespace SymfonyProject\Database;

require ‘Symfonyproject/Database/Connection.php’;

Use Symfonyproject\Database\Connection as Dbconnection;

$Connection=new Dbconnection();

Use SymfonyProject\Database as Symfonydatabase;

$Connection=new Database\Connection();

In short , we we namespace for enhancing flexiblity and more readability to our code and avoid ourselves from fatal errors.