Table of Contents
6. Classes & Autoloading — How Modern PHP Organizes Code
Why this matters
Modern PHP relies on:
- classes, namespaces, autoloading, predictable file structure
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:
- properties (state)
the data an object carries - methods (behavior)
what the object can do
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:
- naming conflicts
two classes with the same name - global clutter
everything dumped into the root namespace - accidental collisions
especially in large or modular projects
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:
- Namespace → Folder
- Class name → File name
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
- Instance methods use
$this
tied to the state of an object - Static methods do not
they belong to the class, not an instance
AI often mixes these incorrectly.
Our understanding helps us correct it.
6. Classes do not persist between requests
Just like variables and functions:
- classes, objects, static properties,
…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.
- Next: Error Handling
