Namespaces in PHP, are used to group classes, interfaces etc under a given name, so that same names does not conflict with each other. By keeping same names under different namespaces, name collision can be avoided.
File with Same name cannot exists in same folder or directory, Similarly in PHP classes, interfaces etc with same name cannot exists in same PHP program.
Without namespaces, Using same name for class, interface, traits, abstract class, function or constants gives error in PHP program, because of name confliction or collision. To overcome this name confliction problem, PHP provides namespaces, so same name can be used or kept under different namespaces.
- Namespace can contain class, interface, traits, abstract class, function and constants.
- It provides logical grouping or act as container.
- Same name should not be used in namespace.
- Same names must be used in different namespaces to avoid naming collision.
- It avoids name confliction between your code and PHP built-in or third-party classes/trait/interfaces/functions etc.
Syntax
<?php
namespace namespace_name;
// PHP Code
?>
Creating Namespace
Namespace must be written at the top of the code. To create a namespace, namespace keyword is used, followed by name and semicolon.
<?php
namespace myName;
// PHP Code
?>
Multiple Namespaces in same file
PHP allows to create multiple namespaces in a single PHP script.
<?php
namespace myName1;
// PHP Code
namespace myName2;
// PHP Code
namespace myName3;
// PHP Code
?>
Namespace Name collision
To avoid name collision same class name is used and kept under different namespaces.
<?php
namespace myName1;
class Math{
}
namespace myName2;
class Math{
}
?>
Namespace Alias
Alias is use to provide a short or easier name to namespaces or a class. PHP provides use keyword to create an alias.
File name: MobilePhone.php
<?php
namespace MobilePhone;
echo "Hello";
?>
MobilePhone.php file namespace MobilePhone is used in index.php file.
- First include a file which has namespaces.
- To use namespaces of included file, PHP use and as keyword is used.
File name: index.php
<?php
include "MobilePhone.php";
use MobilePhone as Samsung;
?>
Sub namespaces
Sub namespaces allows to create a namespace inside a namespace, it is like hierarchy or sub-levels.
sub namespaces are separated by backslash.
Syntax
namespace namespace\subnamespace\subnamespace
Example
<?php
namespace namespace\namespace\namespace3
?>