Skip to main content

Lesson 3 of 7

Namespaces - Organising PHP Code

Namespaces prevent class name collisions - two libraries can both have a class named Request without conflict. They also organise code into logical groups mirroring the filesystem. Modern PHP with Composer uses namespaces extensively and follows PSR-4 for mapping namespace + class name to file path.

12 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Namespaces & the use Statement

Namespaces & the use Statement
<?php
declare(strict_types=1);

// ── Declaring a namespace - FIRST line after <?php declare() ────
namespace App\Blog\Domain;

// ── Class in a namespace ────────────────────────────────────────
class Post {
    // Fully qualified name: App\Blog\Domain\Post
}

// ── In another file ────────────────────────────────────────────
namespace App\Blog\Repository;

use App\Blog\Domain\Post;                       // import class
use App\Blog\Domain\{Post, Author, Category};   // import multiple
use App\Blog\Repository\PostRepositoryInterface as PostRepo; // alias

class PdoPostRepository implements PostRepo {
    public function findById(int $id): ?Post { /* ... */ return null; }
}

// ── Sub-namespaces mirror folder structure (PSR-4) ────────────
// src/
// ├── Blog/
// │   ├── Domain/
// │   │   ├── Post.php       → namespace App\Blog\Domain;
// │   │   └── Author.php     → namespace App\Blog\Domain;
// │   ├── Repository/
// │   │   ├── PostRepositoryInterface.php
// │   │   └── PdoPostRepository.php
// │   └── Service/
// │       └── PostService.php
// └── Http/
//     └── Controller/
//         └── PostController.php

// ── Importing global classes, functions, constants ────────────
namespace App\Blog\Service;

use PDO;                      // import global PDO class
use function array_map;      // import global function
use const PHP_EOL;            // import global constant

// Without use, access global namespace with \ prefix:
$pdo = new \PDO("mysql:...", "root", "");

// ── Namespace in use (real example) ───────────────────────────
namespace App\Http\Controller;

use App\Blog\Service\PostService;
use App\Blog\Domain\Post;
use App\Shared\Http\{Request, Response, JsonResponse};

class PostController {
    public function __construct(
        private readonly PostService $postService,
    ) {}

    public function index(Request $request): JsonResponse {
        $posts = $this->postService->getAllPublished();
        return new JsonResponse([
            "data"  => array_map(fn(Post $p) => $p->toArray(), $posts),
            "total" => count($posts),
        ]);
    }

    public function show(Request $request, int $id): JsonResponse {
        $post = $this->postService->getPost($id);
        return new JsonResponse(["data" => $post->toArray()]);
    }
}

Quick Quiz

Tip

Tip

Practice Namespaces Organising PHP Code in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Visual architecture and concepts for Namespaces - Organising PHP Code

Practice Task

Note

Practice Task - (1) Write a working example of Namespaces Organising PHP Code from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Common Mistake

Warning

A common mistake with Namespaces Organising PHP Code is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready php code.

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/7 done