PHP Namespaces
In this page:
What are Namespaces?
A namespace groups related classes, functions, and constants under a common prefix, solving naming collisions that would otherwise occur if two different libraries both defined a class called Response.
Example: What are Namespaces?
<?php
namespace App\Models;
class Response {
function send() {
echo "App\\Models\\Response";
}
}
$r = new Response();
$r->send();
?>
Login to try C/C++/Java/PHP code in the editor
Declaring Namespaces
You declare a namespace with the namespace keyword as the very first statement in a file, like namespace App\Models;, and PHP treats everything after that declaration as belonging to that namespace.
Example: Declaring Namespaces
<?php
namespace App\Models;
class User {
function __construct() {
echo "User in namespace: " . __NAMESPACE__;
}
}
new User();
?>
Login to try C/C++/Java/PHP code in the editor
Using Namespaces
The use keyword imports a namespaced class into the current file so you can refer to it by its short name instead of writing out the full namespaced path every time you use it.
Example: Using Namespaces
<?php
namespace App\Models {
class User {
function hello() { echo "Hello from User"; }
}
}
namespace App {
use App\Models\User;
$user = new User();
$user->hello();
}
?>
Login to try C/C++/Java/PHP code in the editor
The use Keyword
A leading backslash, like \DateTime, refers to a class in the global namespace, which matters when you're inside a custom namespace and need to explicitly reach a built-in PHP class rather than a same-named class of your own.
Example: The use Keyword
<?php
namespace App;
class DateTime {
function today() {
return (new \DateTime())->format("Y-m-d");
}
}
$d = new DateTime();
echo $d->today();
?>
Login to try C/C++/Java/PHP code in the editor
Sub-Namespaces
Namespaces are the foundation Composer's autoloading relies on, mapping namespace paths to folder structures so that classes from third-party packages can be loaded automatically without manual require statements.
Example: Sub-Namespaces
<?php
namespace App\Services\Payment;
class Gateway {
function charge() {
echo "Charging via " . __NAMESPACE__ . "\\Gateway";
}
}
(new Gateway())->charge();
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first: