Table of Contents

6. Classes & Autoloading — How Modern PHP Organizes Code

Why this matters

Modern PHP relies on:

AI often generates code that looks object‑oriented but violates these conventions.
Your mental model helps you see when something is out of place.

1. Classes are containers for behavior and state

A class defines:

class User {
    public string $name;
    public function greet(): string {
        return "Hello, {$this->name}";
    }
}

Objects created from the class live only for the duration of the request
— there is no persistent memory unless you build it yourself.


2. Namespaces prevent collisions

Namespaces give structure:

namespace App\Models;
class User { ... }

They prevent:

AI sometimes invents namespaces that don’t exist.
Your mental model helps you catch that instantly.


3. Autoloading connects namespaces to file paths

Modern PHP uses PSR‑4 autoloading, which maps:

Example:

App\Models\User

maps to:

src/Models/User.php

If the structure doesn’t match, autoloading breaks
— and this is one of the most common AI‑generated errors..


4. Autoloaders load classes only when needed

PHP does not load every class at the start.
It loads a class the moment it is first referenced.

This keeps memory usage low and performance predictable
— a natural fit for PHP’s request‑driven model.


5. Static vs instance methods

AI often mixes these incorrectly.
Our understanding helps us correct it.


6. Classes do not persist between requests

Just like variables and functions:

all disappear when the request ends.

There is no long‑running application memory unless you build it yourself
(using workers, caches, queues, or external services).


Summary

Modern PHP’s class model is: - structured
- predictable
- filesystem‑driven
- namespace‑aware
- autoloaded on demand

Once we internalize this,
we can immediately see when AI‑generated code “feels wrong”
— even before we run it.