Before namespaces (PHP 5.3+), every class in the global scope needed a unique name, leading to painfully long class names like Zend_Db_Adapter_Pdo_Mysql. Namespaces fixed that, and PSR-4 gave the ecosystem a consistent autoloading convention on top.
Declaring and Using Namespaces
// src/App/Services/PaymentService.php
namespace App\Services;
class PaymentService {
public function charge(float $amount): bool {
return $amount > 0;
}
}
// elsewhere
use App\Services\PaymentService;
$service = new PaymentService();
$service->charge(19.99);
PSR-4: Mapping Namespaces to Files
{
"autoload": {
"psr-4": { "App\\": "src/" }
}
}
With this mapping, App\Services\PaymentService automatically resolves to src/Services/PaymentService.php — no manual require statements needed anywhere in the codebase.