← Back to PHP Course | Chapter 8: OOP | Lesson 12 of 14

PHP Namespaces

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
<?php
namespace App\Models;

class Response {
    function send() {
        echo "App\\Models\\Response";
    }
}
$r = new Response();
$r->send();
?>

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
<?php
namespace App\Models;

class User {
    function __construct() {
        echo "User in namespace: " . __NAMESPACE__;
    }
}
new User();
?>

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
<?php
namespace App\Models {
    class User {
        function hello() { echo "Hello from User"; }
    }
}

namespace App {
    use App\Models\User;
    $user = new User();
    $user->hello();
}
?>

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
<?php
namespace App;

class DateTime {
    function today() {
        return (new \DateTime())->format("Y-m-d");
    }
}
$d = new DateTime();
echo $d->today();
?>

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
<?php
namespace App\Services\Payment;

class Gateway {
    function charge() {
        echo "Charging via " . __NAMESPACE__ . "\\Gateway";
    }
}
(new Gateway())->charge();
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.