📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials PHP for Beginners Namespaces

Namespaces

5 min read Quiz at the end
Namespaces organize PHP code and prevent naming conflicts between classes from different libraries. Use namespace at the top of the file and import classes with use. Essential when building large apps with Composer packages.

Namespaces

// Declare namespace (must be first line)
namespace App\Models;

class User {
    public string $name;
}

// ─────────────────────────────

namespace App\Controllers;

use App\Models\User;
use App\Services\AuthService as Auth;

class UserController {
    public function __construct(private Auth $auth) {}

    public function show(int $id): void {
        $user = new User();
        // ...
    }
}

// ─────────────────────────────
// Global namespace
namespace {
    $user = new \App\Models\User();
}
Topic Quiz · 5 questions

Test your understanding before moving on

1. What is the purpose of namespaces?
💡 Namespaces prevent class/function name collisions, especially in large projects.
2. Which keyword declares a namespace?
💡 namespace MyApp\Controllers; at the top of the file.
3. How do you import a class from another namespace?
💡 use App\Models\User; imports the class for use without full path.
4. What does the use...as syntax do?
💡 use App\Models\User as U; creates an alias so you can use U instead of User.
5. The global namespace is accessed with:
💡 \ClassName references the global namespace, useful inside namespaced code.