You create a namespace with the namespace keyword at the top of the file, before any other code (except declare).
<?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
namespacemust be the first statement in the file. Onlydeclare(...)may come before it.- Only one namespace per file is the convention (PSR-4 expects it).
- Namespace names use backslashes
\as separators. - By convention, they use PascalCase.
Sub-namespaces
A backslash makes a hierarchy:
App
├── Shop
│ ├── Product
│ └── Cart
└── Http
└── Controllers
└── ProductController
In code: App\Shop\Product, App\Http\Controllers\ProductController.
Using the class from another file
<?php
namespace App\Shop;
class Product
{
public function __construct(public string $name) {}
}
<?php
require_once __DIR__ . "/src/Shop/Product.php";
$product = new App\Shop\Product("Pen");
echo $product->name . " / " . get_class($product);
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.
<?php
namespace App\Shop;
class Cart {}
$c = new Cart(); // App\Shop\Cart
echo get_class($c);
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.
<?php
namespace App\Shop;
$d = new \DateTime("2026-01-15"); // leading backslash: the global DateTime
echo $d->format("Y");
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__
<?php
namespace App\Shop;
echo __NAMESPACE__;
App\Shop
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.