iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

PHP Namespaces

A namespace is a folder for class names. Without them, every class shares one global pool — a recipe for collisions once a project grows past trivial.

Declare

PHP — src/Billing/Invoice.php
<?php
namespace App\Billing;

class Invoice {
    public function ref(): string { return 'INV-001'; }
}

Use it

PHP
<?php
use App\Billing\Invoice;
use App\Billing\Invoice as Bill;     // alias
use App\Billing\{Invoice, Payment};   // grouped

$inv = new Invoice();
echo $inv->ref();

Fully qualified vs relative

PHP
$inv = new \App\Billing\Invoice();   // fully qualified — leading backslash
$inv = new Invoice();                  // after `use`, this is unambiguous

PSR-4 + Composer autoloading

Standard convention — file paths mirror namespace paths:

composer.json
{
    "autoload": {
        "psr-4": {
            "App\\": "src/"
        }
    }
}

Then App\Billing\Invoice lives at src/Billing/Invoice.php. Run composer dump-autoload after adding new namespaces and the autoloader takes care of require.

Sub-namespaces

PHP
namespace App\Billing\Reports;

use App\Billing\Invoice;             // can import siblings
class MonthlySummary { ... }
Tip: One namespace per directory, one class per file. Tooling (IDEs, autoload, refactoring) all assume this convention — fight it and everything gets harder.

Example

Example
<?php
namespace Shop\Billing;
class Invoice {
    public function ref(): string { return 'INV-001'; }
}
use Shop\Billing\Invoice;
echo (new Invoice())->ref();
Try it Yourself »

Exercise

Declare a namespace.

App\Billing;

Test yourself

Q1. Namespaces map to…
Q2. Bring a class in with…
Q3. Fully qualified name starts with…

Discussion

Loading…