PHP Namespaces

Ma Mahalakshmi V Updated 14 Nov 2026
5 min read ·Lesson 175 of 256

What Is a Namespace?

In simple terms: A namespace is like a folder for names. Two files can both be called report.pdf if they live in different folders; likewise, two classes can both be called Invoice if they live in different namespaces — App\Billing\Invoice and App\Shipping\Invoice. Namespaces prevent name collisions and organize code into logical groups.

Technically: A namespace is declared with the namespace keyword at the top of a file. Classes, interfaces, traits, enums, functions, and constants declared in that file belong to the namespace. Their fully qualified name includes the namespace, separated by backslashes. The use statement imports names so they can be referred to by a shorter name.

Why Namespaces Are Needed

Modern applications combine their own code with dozens of Composer packages. Without namespaces, every class name in every package would have to be globally unique — a Logger class in your project would clash with a Logger class in a library. With namespaces, each vendor has its own space: Monolog\Logger, App\Support\Logger, and so on.


Declaring a Namespace

Normally, each file contains one namespace declaration as its first statement:

<?php
// src/Billing/Invoice.php
declare(strict_types=1);

namespace App\Billing;

final class Invoice
{
    public function __construct(public readonly string $number) {}
}
  • The namespace statement must come before any other code (only declare may precede it).
  • The class's full name is now App\Billing\Invoice.
  • By convention (PSR-4), the namespace mirrors the folder structure: App\Billing\Invoice lives in src/Billing/Invoice.php. This convention allows classes to be loaded automatically (see Autoloading Classes).

Using Names From Other Namespaces

The following example puts several namespaces in one file using the bracketed syntax, so it can be run as a single script. (In real projects, use one namespace per file.)

<?php
namespace App\Billing {
    final class Invoice
    {
        public function type(): string
        {
            return __CLASS__;
        }
    }
}

namespace App\Shipping {
    final class Invoice
    {
        public function type(): string
        {
            return __CLASS__;
        }
    }
}

namespace {
    use App\Billing\Invoice;
    use App\Shipping\Invoice as ShippingInvoice;

    echo (new Invoice())->type() . "\n";
    echo (new ShippingInvoice())->type() . "\n";
    echo (new \App\Billing\Invoice())->type() . "\n";
    echo Invoice::class . "\n";
}

Output

App\Billing\Invoice
App\Shipping\Invoice
App\Billing\Invoice
App\Billing\Invoice

How It Works

  1. Two classes named Invoice coexist because they are in different namespaces.
  2. use App\Billing\Invoice; imports the class: in this file, Invoice now means App\Billing\Invoice.
  3. use ... as ShippingInvoice imports the second Invoice under an alias, avoiding a conflict in this file.
  4. A name beginning with `` is fully qualified and works without any import.
  5. Invoice::class resolves the imported name to its full class name at compile time.
  6. The block namespace { ... } contains code in the global namespace.

Types of Names

NameExampleResolved As
UnqualifiedInvoiceImported name, or current namespace + Invoice
QualifiedBilling\InvoiceCurrent namespace + Billing\Invoice (unless the first part is imported)
Fully qualified\App\Billing\InvoiceExactly as written

Global Classes Inside a Namespace

Inside a namespace, an unqualified class name always refers to the current namespace — even for PHP's built-in classes:

<?php
namespace App\Orders;

try {
    throw new Exception('Payment failed');
} catch (\Error $e) {
    echo $e->getMessage() . "\n";
}

Output

Class "App\Orders\Exception" not found

PHP looked for App\Orders\Exception. Built-in classes live in the global namespace, so they must be imported or written with a leading backslash:

use Exception;               // option 1: import
throw new \Exception('...'); // option 2: fully qualified

Functions and Constants Fall Back to Global

Functions and constants behave differently: if App\Orders\strlen() does not exist, PHP falls back to the global strlen(). That is why calling strlen(), count(), or using PHP_EOL inside a namespace works without a backslash. Some projects still write \strlen() or import functions (use function strlen;) to skip the fallback lookup, which gives a small performance benefit for certain optimized built-in functions.


Importing Functions and Constants

<?php
namespace App\Support {
    const CURRENCY = 'INR';

    function money(int $paise): string
    {
        return '₹' . number_format($paise / 100, 2);
    }
}

namespace App\Reports {
    use function App\Support\money;
    use const App\Support\CURRENCY;

    echo money(129900) . ' (' . CURRENCY . ")\n";
}

Output

₹1,299.00 (INR)

use function and use const import namespaced functions and constants, just as use imports classes.

Group Imports

Several names from the same namespace can be imported together:

use App\Billing\{Invoice, InvoiceLine, PaymentStatus};

Useful Namespace Helpers

ExpressionValue
__NAMESPACE__The current namespace as a string (empty in the global namespace)
ClassName::classThe fully qualified class name
namespace\helper()Explicitly refers to helper() in the current namespace
static::class, get_class($obj)Full class name of an object at runtime

Organizing a Project With Namespaces

A typical structure for an application with the root namespace App:

project/
├── composer.json           "autoload": { "psr-4": { "App\\": "src/" } }
└── src/
    ├── Billing/
    │   ├── Invoice.php     namespace App\Billing;   class Invoice
    │   └── InvoiceService.php
    ├── Catalog/
    │   ├── Product.php     namespace App\Catalog;   class Product
    │   └── ProductRepository.php
    └── Support/
        └── Money.php       namespace App\Support;   class Money

Guidelines

  • Use a vendor or project prefix as the root (App, GoCourse, Acme\Shop).
  • Group by feature or domain (Billing, Catalog, Shipping) rather than by technical type alone.
  • Use PascalCase for namespace segments, matching the folder names exactly (paths are case-sensitive on Linux servers).
  • Put one class per file, with the file named after the class.

Common Mistakes

Forgetting the Backslash for Global Classes

Effect: Class "App0..\Exception" not found or DateTime not found.

Fix: use Exception; or new \Exception().

Code Before the namespace Statement

Effect: Fatal error: the namespace declaration must be the first statement.

Fix: Only <?php and declare(...) may come before it.

Namespace Does Not Match the Folder

Effect: The autoloader cannot find the class.

Fix: Keep namespaces and directories in sync (PSR-4).

Importing Two Classes With the Same Short Name

Effect: Fatal error: "Cannot use ... because the name is already in use".

Fix: Use an alias with as.

Using use Inside Functions

Effect: Syntax error — use imports must be at the top level of the file (the use in closures is unrelated).

Fix: Place imports after the namespace declaration.


Best Practices

  • Declare exactly one namespace per file, matching its directory (PSR-4).
  • Import classes with use at the top of the file, sorted alphabetically.
  • Use aliases only when names collide, and choose descriptive alias names.
  • Import or fully qualify global classes inside namespaces.
  • Use namespaces to group code by domain or feature.

Official reference: https://www.php.net/manual/en/language.namespaces.php

0 Comments

Reviewed before they appear

No comments yet.

PHP
PHP Tutorial Index PHP Home PHP Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope Static Variables Variable Variables PHP Echo / Print PHP printf / sprintf PHP Data Types PHP Booleans PHP NULL PHP Strings String Functions Modify Strings Concatenate Strings Slicing Strings Escape Characters String Interpolation Heredoc and Nowdoc Search in Strings Multibyte Strings PHP Floats PHP Casting PHP Type Juggling PHP Math PHP Random Numbers PHP Constants PHP Magic Constants PHP Operators Arithmetic Operators Assignment Operators Comparison Operators Increment / Decrement Operators Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence PHP If...Else...Elseif PHP If PHP If Operators PHP If...Else PHP Shorthand if PHP Nested if PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement Continue Statement PHP Functions User-defined Functions Function Arguments Default Argument Values Pass by Reference Named Arguments Variadic Functions Return Values Type Declarations in Functions Recursive Functions Variable Functions Anonymous Functions Closures Arrow Functions First-class Callable Syntax PHP Arrays Indexed Arrays Associative Arrays Create Arrays Access Array Items Update Array Items Add Array Items Remove Array Items Sorting Arrays Multidimensional Arrays Array Destructuring Array Spread Operator Search in Arrays Merge Arrays array_map / array_filter / array_reduce Array Functions PHP Superglobals $GLOBALS $_SERVER $_REQUEST $_POST $_GET $_FILES $_COOKIE $_SESSION \$\_ENV PHP RegEx RegEx Patterns RegEx Modifiers preg_match preg_replace preg_split PHP RegEx Functions PHP Form Handling PHP Form Validation PHP Form Required PHP Form URL/E-mail Form Input Sanitizing Escaping Output (htmlspecialchars) Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting DateTime Class Timezones PHP Include Include vs Require PHP File Handling PHP File Open/Read PHP File Create/Write File Delete / Rename / Copy PHP Directories PHP CSV Files PHP File Upload PHP Cookies PHP Sessions PHP Filters PHP Filters Advanced PHP Callback Functions PHP JSON PHP Exceptions Error Handling Custom Error Handler Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators PHP What is OOP PHP Classes/Objects The $this Keyword PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Destructor PHP Access Modifiers Readonly Properties PHP Inheritance Method Overriding The final Keyword PHP Class Constants PHP Abstract Classes PHP Interfaces Polymorphism PHP Traits PHP Static Methods PHP Static Properties Late Static Binding Magic Methods Object Cloning Comparing Objects Anonymous Classes PHP Enums PHP Namespaces Autoloading Classes PHP Iterables Iterators Object Serialization Strict Types Union Types Nullable Types Mixed and Never Types Nullsafe Operator PHP Attributes PHP Fibers Readonly Classes Property Hooks (PHP 8.4) Asymmetric Visibility (PHP 8.4) Reflection API SPL Data Structures MySQL Database MySQL Connect MySQL Create DB MySQL Create Table MySQL Insert Data MySQL Get Last ID MySQL Insert Multiple MySQL Prepared MySQL Select Data MySQL Where MySQL Order By MySQL Delete Data MySQL Update Data MySQL Limit Data MySQL Joins with PHP Pagination with PHP PDO Introduction PDO Connect PDO Prepared Statements PDO Fetch Modes PDO Transactions PDO Error Handling PHP XML Parsers PHP SimpleXML Parser PHP SimpleXML - Get PHP XML Expat Parser PHP DOM Parser PHP XMLReader PHP XMLWriter AJAX Intro AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll AJAX with JSON Security Introduction Password Hashing SQL Injection Prevention XSS Prevention CSRF Protection Session Security Secure Cookies File Upload Security Filesystem Security Error Reporting in Production Hiding PHP Encryption with Sodium PHP Configuration (php.ini) PHP Command Line (CLI) Composer PSR-4 Autoloading Installing Extensions (PECL / PIE) Debugging PHP OPcache & Performance Garbage Collection PHP-FPM Migrating to PHP 8 Project: Contact Form with Email Project: Login & Registration System Project: CRUD App with MySQL Project: Image Upload Gallery Project: Shopping Cart with Sessions Project: Simple Blog Project: REST API with PHP
Ask about this post
AI Ask about this post

Ask questions about PHP Namespaces and get answers drawn from it.

Signed-in readers only.