What is it?
Namespaces group related classes under a unique path to prevent name collisions. Autoloading automatically loads class files on demand so you never need to write require_once manually.
Why does it matter?
As projects grow past 10 files, manually requiring every class becomes unmaintainable and collision-prone. Namespaces plus autoloading is the professional standard used by every modern PHP framework.
Learn PHP namespaces, the use keyword, aliasing, and Composer PSR-4 autoloading.
Real-World Use Cases
- 🏗️ Large application structure - Organise controllers in App\Http\Controllers, models in App\Models, services in App\Services — each file auto-loaded on demand.
- 📦 Third-party packages - Composer installs packages with their own namespaces — your code and vendor code coexist without any name conflicts.
- 🔄 Multiple database drivers - Have App\Database\MySQL and App\Database\PostgreSQL classes both named Connection — namespaces keep them separate.
- 🧪 Test isolation - Put tests under Tests\Unit and Tests\Integration namespaces, completely separate from production code.
Defining a Namespace
<?php
namespace App\Models;
class User {
public function hello() {
echo "Hello User";
}
}
?>
Using Namespaced Classes
<?php
require 'User.php';
use App\Models\User;
$user = new User();
$user->hello();
// or directly
$user = new App\Models\User();
?>
Composer PSR-4 Autoloading
{
"autoload": {
"psr-4": {
"App\\": "app/"
}
}
}
Q: Do I need Composer just for autoloading?
Composer PSR-4 autoloading is free and the industry standard, even with no third-party packages. It is simpler than spl_autoload_register and works with every modern PHP framework
Comments (0)
No comments yet. Be the first!
Leave a Comment