Skip to content

PHP Tutorial Namespaces and Autoloading

Using Namespaces with use

Lesson 241 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

The use keyword imports a name, so you can write Product instead of App\Shop\Product.

src/Shop/Product.php
PHP
<?php

namespace App\Shop;

class Product
{
    public function __construct(public string $name) {}
}
index.php
PHP
<?php
require_once __DIR__ . "/src/Shop/Product.php";

use App\Shop\Product;

$p = new Product("Notebook");

echo $p->name;
Output
OUTPUT
Notebook

Put use lines at the top of the file, after namespace and before the code.

Import built-in classes too

Inside a namespace, global classes need a backslash or an import.

index.php
PHP
<?php
namespace App;

use DateTimeImmutable;
use InvalidArgumentException;

$date = new DateTimeImmutable("2026-03-01");

try {
    throw new InvalidArgumentException("example");
} catch (InvalidArgumentException $e) {
    echo $date->format("d M Y") . ": " . $e->getMessage();
}
Output
OUTPUT
01 Mar 2026: example

Aliases with as

If two classes have the same short name, give one an alias.

index.php
PHP
<?php
namespace App;

class Logger
{
    public function who(): string { return "App logger"; }
}

namespace Vendor;

class Logger
{
    public function who(): string { return "Vendor logger"; }
}

namespace Main;

use App\Logger;
use Vendor\Logger as VendorLogger;

echo (new Logger())->who() . "\n";
echo (new VendorLogger())->who();
Output
OUTPUT
App logger
Vendor logger

Group use

Several imports from one namespace can share a line.

index.php
PHP
<?php
use App\Shop\{Product, Cart, Order};

This is the same as three separate use lines.

Importing functions and constants

index.php
PHP
<?php
namespace Utils {
    const GREETING = "Hello";

    function shout(string $text): string
    {
        return strtoupper($text) . "!";
    }
}

namespace Main {
    use function Utils\shout;
    use const Utils\GREETING;

    echo shout(GREETING);
}
Output
OUTPUT
HELLO!

use does not load the file

use only creates a name shortcut. It does not load the class file. PHP still needs to find the class, either through require or through an autoloader. See Autoloading.

Do not import what you do not use

Unused use lines are noise. Editors highlight them, and tools can remove them.

use has other meanings too

The keyword use appears in two other places, and they are unrelated:

  • In closures: function () use ($x) { ... }. See Closures.
  • In classes, for traits: use Timestamps;. See Traits.
lightbulb
A tidy file
Order of a typical file: <?php, declare(strict_types=1);, namespace, use imports, then the class. Editors can sort imports for you.