Skip to content
Tutorials Center
My learning

Topics

Lesson 57 of 147 ยท Object-Oriented PHP

Namespaces

Learn PHP namespaces - declaring them, importing classes, functions and constants with use, aliases, group use, the global fallback rules and PSR-4 folders.

Every real PHP application uses code written by other people: a framework, a mail library, a PDF generator, a logging package. Sooner or later two of them define a class with the same name. Your project has a User class, and so does the authentication library. Your code has a Logger, and so does the monitoring package. Without some way to tell them apart, PHP would stop with Cannot declare class User, because the name is already in use.

Namespaces solve this. A namespace is a named container for classes, interfaces, traits, enums, functions and constants, very much like a folder for files. Two classes called User can live happily side by side as App\Models\User and Vendor\Auth\User. Every modern PHP project, every framework and every Composer package uses namespaces, so reading and writing them fluently is essential.

This lesson covers declaring namespaces, fully qualified names, importing with use (classes, functions and constants), aliases, the global fallback rules that trip up many developers, and how namespaces map to folders. The next lesson builds on this to load classes automatically.

Declaring a namespace

The namespace declaration must be the first statement in a file (only declare(strict_types=1); and comments may come before it). Everything declared after it belongs to that namespace:

PHP
<?php
declare(strict_types=1);

namespace App\Billing;

class Invoice
{
    // ...
}

function formatAmount(int $cents): string
{
    return number_format($cents / 100, 2);
}

const TAX_RATE = 0.2;

This file defines App\Billing\Invoice, App\Billing\formatAmount() and App\Billing\TAX_RATE. The backslash \ separates the levels, like / in a file path. Namespace names are case-insensitive, but by convention they're written in PascalCase and match the class's folder exactly.

Real projects put one namespace per file, and usually one class per file. Our editor runs a single file, so the examples in this lesson use PHP's braced syntax, which allows several namespaces in one file:

PHP
namespace App\Billing {
    // code in App\Billing
}

namespace {
    // code in the global namespace
}

When one file uses braces, every namespace in it must use braces, and no code may sit outside them (except declare). You'll rarely need this outside of demos and tests.

Names: unqualified, qualified and fully qualified

There are three ways to write a name, and PHP resolves each one differently:

Kind Example Resolved relative to
Unqualified Invoice the current namespace (or an import)
Qualified Billing\Invoice the current namespace (or an import of Billing)
Fully qualified \App\Billing\Invoice the global root, always the same

A leading backslash makes a name fully qualified, the same idea as an absolute path starting with /. Without it, the name is relative to the current namespace:

PHP Three ways to name a class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

get_class() and ::class always give the fully qualified name, without the leading backslash: App\Billing\Invoice. The magic constant __NAMESPACE__ holds the current namespace, which is an empty string in the global namespace.

Importing with use

Writing \App\Billing\Invoice everywhere gets long. A use statement imports a name once, at the top of the file, so you can refer to it by its short name:

PHP
<?php
declare(strict_types=1);

namespace App\Http\Controllers;

use App\Billing\Invoice;
use App\Billing\InvoiceRepository;
use Psr\Log\LoggerInterface;

class InvoiceController
{
    public function __construct(
        private InvoiceRepository $invoices,
        private LoggerInterface $logger,
    ) {}

    public function show(int $id): Invoice
    {
        // Invoice here means App\Billing\Invoice
    }
}

use statements are always written with the full name, without a leading backslash (the leading backslash is allowed but pointless, since use names are always fully qualified). Most projects sort them alphabetically. use only creates a shortcut for the current file: it doesn't load anything and doesn't check that the class exists. A typo shows up only when the name is actually used.

Aliases with as

If two imports would have the same short name, or a name is unclear, give one of them an alias with as:

PHP Two User classes with an alias

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Inside App\Services, User means App\Models\User and AuthUser means Vendor\Auth\User. The alias is only a local nickname: AuthUser::class still reports the real name, Vendor\Auth\User.

Importing functions and constants

Plain use imports classes, interfaces, traits and enums. Functions and constants need use function and use const:

PHP
use function App\Billing\formatAmount;
use const App\Billing\TAX_RATE;

echo formatAmount(1999);
echo TAX_RATE;

Group use

When you import several names from the same namespace, a group use declaration keeps it short:

PHP
use App\Billing\{Invoice, InvoiceRepository, Payment as BillingPayment};
use function App\Support\{slugify, money};

Some teams like group use, others prefer one use per line because it makes diffs and merges cleaner. Follow your project's style; PSR-12 allows both.

Global fallback: functions yes, classes no

This is the rule that confuses almost everyone at first. When PHP meets an unqualified name inside a namespace, it behaves differently for functions/constants and for classes:

  • For functions and constants, PHP first looks in the current namespace. If there's nothing there, it falls back to the global namespace. That's why strlen() and PHP_EOL work in every namespace without a backslash.
  • For classes (and interfaces, traits, enums), there's no fallback. new DateTimeImmutable() inside namespace App; looks for App\DateTimeImmutable, and fails if it doesn't exist.
PHP Classes don't fall back to the global namespace

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The last line prints Error: Class "App\Reports\DateTimeImmutable" not found. There are two standard fixes:

  1. Write a leading backslash: new \DateTimeImmutable(), catch (\Exception $e).
  2. Import the class at the top: use DateTimeImmutable;. Many style guides prefer this, so that all dependencies of a file are listed in one place.

Notice the catch (\Error $e) in the example. Catching Exception without a backslash or import inside a namespace is a classic bug: catch (Exception $e) refers to App\Reports\Exception, which doesn't exist, so the catch block silently never matches and the real exception escapes. PHP doesn't complain, because a catch clause for a class that doesn't exist is allowed.

Inside a namespace, always write \Exception, \Throwable, \PDO, \DateTimeImmutable and other built-in classes with a leading backslash, or import them with use. Functions like count() and strlen() work either way.

Some code also writes built-in functions as \strlen() or imports them with use function strlen;. That's a small performance optimization: PHP can resolve a fully qualified call at compile time and use special fast versions of some functions, instead of checking the namespace at run time. It's optional, and tools like PHP-CS-Fixer can add the backslashes for you.

Namespaces and folders: PSR-4

PHP itself doesn't care where a file lives or what namespace it declares. But the whole PHP ecosystem follows one convention, PSR-4: a namespace prefix maps to a base folder, and the rest of the namespace maps to subfolders, with one class per file named after the class.

TEXT
composer.json: "App\\" => "src/"

App\Billing\Invoice             โ†’ src/Billing/Invoice.php
App\Billing\InvoiceRepository   โ†’ src/Billing/InvoiceRepository.php
App\Http\Controllers\HomeController โ†’ src/Http/Controllers/HomeController.php

Because the file path can be computed from the class name, an autoloader can load any class on demand. You'll build one and see how Composer does it in Autoloading and Composer. PSR-4 and other standards are covered in Coding Standards and PSRs.

A typical namespace layout looks like Vendor\Package\Area\ClassName: Symfony\Component\HttpFoundation\Request, Monolog\Handler\StreamHandler, or for your own app simply App\....

Resolving names at run time

Names in strings are always treated as fully qualified. use statements and the current namespace don't apply to them, because they're resolved when the code runs, not when it's compiled:

PHP Class names in strings are always fully qualified

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Two habits come out of this:

  • In strings, write the full name and double the backslashes in single-quoted strings ('App\\Notifications\\SmsChannel'), or, better, avoid strings altogether.
  • Use ClassName::class whenever you need a class name as a string. It's resolved at compile time using your imports, so EmailChannel::class becomes 'App\Notifications\EmailChannel', and IDEs can rename and find it.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Inside namespace App; with no imports, what does new DateTime() try to create?

    Class names never fall back to the global namespace. Write \DateTime or add use DateTime; at the top of the file.
  2. 2. Inside namespace App;, why does strlen("abc") work without a backslash?

    Functions and constants fall back to the global namespace if no namespaced version exists. Classes don't.
  3. 3. Given use Vendor\Auth\User as AuthUser;, what does AuthUser::class contain?

    An alias is only a local nickname. ::class always resolves to the real, fully qualified class name.
  4. 4. Which statement imports a namespaced function?

    Functions are imported with use function and constants with use const. Plain use is for classes, interfaces, traits and enums.
  5. 5. Inside namespace App\Reports;, which name refers to the same class no matter where the code runs?

    A leading backslash makes a name fully qualified, so it never depends on the current namespace or imports.

Summary

  • A namespace groups classes, functions and constants under a name like App\Billing, so code from different sources never clashes.
  • Declare it with namespace App\Billing; as the first statement of a file, one namespace per file in real projects.
  • Names are unqualified (Invoice), qualified (Billing\Invoice) or fully qualified (\App\Billing\Invoice); only the last ignores the current namespace.
  • use imports a name for the current file; as sets an alias; use function and use const import functions and constants; group use imports several at once.
  • Unqualified functions and constants fall back to the global namespace; classes don't, so write \Exception or import it.
  • Names in strings are always fully qualified; prefer ClassName::class.
  • PSR-4 maps namespaces to folders, which makes autoloading possible.

Next: Autoloading and Composer