Skip to content

PHP Tutorial Namespaces and Autoloading

Creating Namespaces

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

You create a namespace with the namespace keyword at the top of the file, before any other code (except declare).

src/Shop/Product.php
PHP
<?php

declare(strict_types=1);

namespace App\Shop;

class Product
{
    public function __construct(public string $name) {}
}

Everything declared in this file (classes, interfaces, traits, enums, functions, constants) now belongs to App\Shop. The full name of the class is App\Shop\Product.

Rules

  1. namespace must be the first statement in the file. Only declare(...) may come before it.
  2. Only one namespace per file is the convention (PSR-4 expects it).
  3. Namespace names use backslashes \ as separators.
  4. By convention, they use PascalCase.

Sub-namespaces

A backslash makes a hierarchy:

Text
PLAIN
App
├── Shop
│   ├── Product
│   └── Cart
└── Http
    └── Controllers
        └── ProductController

In code: App\Shop\Product, App\Http\Controllers\ProductController.

Using the class from another file

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";

$product = new App\Shop\Product("Pen");

echo $product->name . " / " . get_class($product);
Output
OUTPUT
Pen / App\Shop\Product

Writing the full name every time is tiring. The next lesson shows use.

Inside a namespace: names resolve to the same namespace

In a file with namespace App\Shop;, a plain name such as Cart means App\Shop\Cart.

index.php
PHP
<?php
namespace App\Shop;

class Cart {}

$c = new Cart();   // App\Shop\Cart

echo get_class($c);
Output
OUTPUT
App\Shop\Cart

The global namespace

Code without a namespace line lives in the global namespace. Built-in classes such as DateTime, Exception and ArrayObject are in the global namespace.

Inside a namespace, you must refer to them with a leading backslash, or import them with use.

index.php
PHP
<?php
namespace App\Shop;

$d = new \DateTime("2026-01-15");   // leading backslash: the global DateTime

echo $d->format("Y");
Output
OUTPUT
2026

Without the backslash, PHP would look for App\Shop\DateTime and fail.

Functions and constants

Built-in functions (strlen, count) and constants (PHP_EOL) are different. PHP falls back to the global one if no namespaced version exists, so you can write strlen() without a backslash.

__NAMESPACE__

index.php
PHP
<?php
namespace App\Shop;

echo __NAMESPACE__;
Output
OUTPUT
App\Shop
warning
Forgetting the backslash for global classes
new Exception("x") inside a namespace looks for App\Shop\Exception. Write new \Exception("x") or add use Exception; at the top.