PHP Tutorial · Object-Oriented PHP · Lesson 35 of 38
PHP Namespaces
Organise code into namespaces and import classes with use.
Why namespaces?
Namespaces group related classes and prevent name clashes — your App\Models\User and a library's Vendor\Auth\User can coexist.
<?php
// src/Models/User.php
namespace App\Models;
final class User
{
public function __construct(public string $name) {}
}
<?php
// src/Controllers/UserController.php
namespace App\Controllers;
use App\Models\User;
use DateTimeImmutable; // global classes need a use (or a leading \)
final class UserController
{
public function show(): string
{
$user = new User("Ada");
return $user->name . " at " . (new DateTimeImmutable())->format("H:i");
}
}
- The namespace usually mirrors the folder structure (PSR-4), which lets Composer autoload classes.
use Foo\Bar as Baz;imports with an alias.ClassName::classgives the fully qualified name as a string.
<?php
namespace App\Models;
class User
{
public function __construct(public string $name) {}
}
$user = new User("Ada");
echo User::class, "\n";
echo get_class($user), " named ", $user->name, "\n";
echo \strtoupper("global functions still work"), "\n";
Output
App\Models\User App\Models\User named Ada GLOBAL FUNCTIONS STILL WORK
Test yourself
What does User::class return?
A new User objectThe fully qualified class name as a stringThe class file pathAn array of methods
Show answer
Answer: The fully qualified class name as a string