PHP: Namespaces and Autoloading

For small projects, 3 classes are enough. But a real application might have 300 classes plus third-party libraries—namespaces and Composer are PHP's "organization system" that prevents name collisions in your code.

1. Why Do We Need Namespaces?

PHP
<?php
// Imagine you wrote a Logger class
class Logger {
    public function log(string $msg): void {
        echo "My log: {$msg}<br>";
    }
}

// You want to use a third-party package that also has a Logger class
// Result: PHP Fatal Error: Cannot redeclare class Logger
?>

Namespaces solve this problem—think of them as giving each class a "last name":

TEXT 📖 参照専用
Without namespace: Logger ← collision!
With namespace:    MyApp\Logger  vs  Vendor\Logger ← no collision!

2. Declaring a Namespace

PHP
<?php
// file: app/Utils/Logger.php
namespace App\Utils;

class Logger {
    public function log(string $msg): void {
        echo "[LOG] {$msg}<br>";
    }
}

// Use the fully qualified name
$log = new \App\Utils\Logger();
$log->log("App started");
?>

Namespace rules:


3. use — Importing Classes

PHP
<?php
namespace App\Controllers;

// After use import, you can use the short class name
use App\Utils\Logger;
use PDO;
use DateTime;

class UserController {
    public function index(): void {
        $log = new Logger();  // No need for the fully qualified name
        $log->log("Viewing user list");
        
        $now = new DateTime();  // PHP built-in classes can also be imported
    }
}
?>

(1) use ... as — Aliases

PHP
<?php
// Resolve name conflicts
use App\Models\User as AppUser;
use Vendor\Cms\User as CmsUser;

$u1 = new AppUser();
$u2 = new CmsUser();
?>

4. Composer — PHP's Package Manager

Composer is to PHP what npm is to Node.js, and pip is to Python.

(1) Installing Composer

Visit https://getcomposer.org to download and install. Then, in your project directory:

BASH
# Initialize the project
cd myphp
composer init

# Install a package (using the popular .env config library as an example)
composer require vlucas/phpdotenv

▶ サンプル: composer.json Configuration and Autoloading

JSON
{
    "name": "myphp/demo",
    "description": "PHP Learning Project",
    "require": {
        "php": ">=8.0",
        "vlucas/phpdotenv": "^5.0"
    },
    "autoload": {
        "psr-4": {
            "App\\": "app/"
        }
    }
}

(2) Using Autoloading

PHP
<?php
// You only need to require this one file
require __DIR__ . '/vendor/autoload.php';

// Now you can use all Composer-managed packages and your custom classes
use App\Models\User;

$user = new User();
?>

5. PSR-4 Autoloading

PSR-4 is the PHP community's autoloading standard—namespace prefix maps to directory:

Namespace Directory Class File Path
App\ app/ app/ is the root
App\Models\User app/Models/User.php
App\Controllers\Admin\Dashboard app/Controllers/Admin/Dashboard.php

▶ サンプル: PSR-4 Project Structure

TEXT 📖 参照専用
myphp/
├── app/
│   ├── Models/
│   │   └── User.php          ← namespace App\Models;
│   └── Controllers/
│       └── UserController.php ← namespace App\Controllers;
├── vendor/                   ← Created automatically by Composer
│   └── autoload.php
├── composer.json
└── public/
    └── index.php
PHP
<?php
// app/Models/User.php
namespace App\Models;

class User {
    public function __construct(
        public string $name,
        public string $email
    ) {}
}
PHP
<?php
// public/index.php
require __DIR__ . '/../vendor/autoload.php';

use App\Models\User;

$user = new User("John", "john@example.com");
echo $user->name;  // John
?>

6. Common Composer Commands

BASH
# Install all dependencies listed in composer.json
composer install

# Add a new dependency
composer require guzzlehttp/guzzle
composer require --dev phpunit/phpunit  # Dev environment only

# Update all dependencies
composer update

# Update a specific package
composer update guzzlehttp/guzzle

# Generate optimized autoloader (production)
composer dump-autoload -o

7. Built-in Classes vs. Namespaces

PHP
<?php
namespace App;

// Inside a namespace, call PHP built-in classes
$date = new \DateTime();          // Root namespace \
$pdo  = new \PDO($dsn, $user, $pass);

// Or use
use DateTime, PDO;

$date = new DateTime();
$pdo  = new PDO($dsn, $user, $pass);
?>
💡 Tip: Inside a namespace, PHP built-in classes must be prefixed with \ or imported with use. Without it, PHP looks in the current namespace (e.g., App\DateTime), which doesn't exist.

❓ よくある質問

Q Do namespaces have to match file paths?
A PSR-4 requires consistency, but PHP syntax doesn't enforce it. You can name things arbitrarily when manually requiring files. But following the standard is what makes Composer's autoloading work.
Q Where are Composer packages installed?
A In the vendor/ directory. This directory is usually not committed to Git (configured in .gitignore). Team members run composer install themselves.
Q What does ^5.0 mean in composer.json?
A It's a semantic versioning (SemVer) constraint. ^5.0 means accept versions >=5.0 and <6.0. ~5.0 means >=5.0 and <5.1.

📖 まとめ

📝 練習問題

  1. Create a simple project structure: app/Models/User.php and app/Utils/Validator.php, each with their own namespace declarations. Import and use them in public/index.php with use.
  2. Install Composer, use composer init to initialize a project, and configure PSR-4 autoloading in composer.json.
  3. Install a third-party package (like ramsey/uuid for generating UUIDs) and understand the role of the vendor directory and autoload.php.
Web-Tutorial.com

Web-Tutorial 技術チーム

複数の開発者によって共同維持されているプログラミングチュートリアルプラットフォーム。各チュートリアルは専門分野の開発者が執筆・レビューしています。正確で信頼性の高いコンテンツを目指しています — 問題を見つけた場合はお知らせください。

100%