PHP namespaces allow you to group related classes, interfaces, functions, and constants. It also helps to avoid Name collisions between code you create, and internal PHP classes or functions or constants or third-party.
- How to declare a namespace?
- PHP namespaces with functions.
- Avoid name collisions.
- PHP namespaces with classes.
- Namespace with hierarchy.
- Namespace Alias.
How to declare a namespace in PHP?
The namespace
keyword is used to declare namespaces at the beginning of a PHP file.
<?php
namespace NameOfTheNamespace;
Example of Namespace
<?php
namespace MyGroup;
function sayHello(){
echo "Hello";
}
function sayHi(){
echo "Hi";
}
How to call a function through a Namespace name?
Use the following syntax to call a function through a Namespace name.
<?php
// Syntax
NameOfTheNamespace\functionName();
Example:
<?php
namespace MyGroup;
function sayHello(){
echo "Hello";
}
function sayHi(){
echo "Hi";
}
<?php
require './test.php';
MyGroup\sayHello();
[Running] php "./index.php"
Hello
How does PHP namespace help to avoid name collisions?
In the following, you can see there are two files test1.php
and test2.php
and both files have a function with the same name sayHello()
.
<?php
function sayHello(){
echo "Hello";
}
<?php
function sayHello($name){
echo "Hello $name";
}
What if we include these two files in one file?
You will get a redeclaration error.
<?php
require "./test1.php";
require "./test2.php";
PHP Fatal error: Cannot redeclare sayHello() (previously declared in..
Use the Namespace to solve this error
<?php
namespace Test1;
function sayHello(){
echo "Hello\n";
}
<?php
namespace Test2;
function sayHello($name){
echo "Hello $name";
}
<?php
require "./test1.php";
require "./test2.php";
Test1\sayHello();
Test2\sayHello("John");
Hello
Hello John
PHP namespaces with classes
The following example shows you how to use PHP namespaces with classes.
<?php
namespace MyNewGroup;
class MyClass{
public function sayHello(){
echo "Hello World";
}
}
<?php
require './test.php';
$obj = new MyNewGroup\MyClass();
$obj->sayHello();
Hello World
Declare namespace with hierarchy
You can write the name of a namespace in a hierarchical way.
<?php
namespace Production\API\V2;
class MyClass{
public function sayHello(){
echo "Hello World";
}
}
<?php
require "./test.php";
$obj = new Production\API\V2\MyClass();
$obj->sayHello();
Namespace Alias
The use
keyword is used to make an alias of the name of a namespace to make the namespace name easier to write.
<?php
namespace Production\API\V2;
function sayHi(){
echo "Hi\n";
}
function sayHello(){
echo "Hello World";
}
<?php
require "./test.php";
use Production\API\V2 as TestName;
TestName\sayHi();
TestName\sayHello();
Hi
Hello World