PHP 8 interview question · Most asked
How does Composer autoloading work, and what is PSR-4?
Summary
PSR-4 maps a namespace prefix to a base directory so App\Models\User loads from src/Models/User.php. Composer generates an autoloader from composer.json that requires files on first use.
Longer Answer
You configure "autoload": {"psr-4": {"App\\": "src/"}} and include vendor/autoload.php. Composer registers an spl_autoload_register callback. In production, run composer dump-autoload --optimize (or --classmap-authoritative) to generate a class map and avoid filesystem lookups.
Code Example
{
"autoload": {
"psr-4": { "App\\": "src/" }
},
"autoload-dev": {
"psr-4": { "Tests\\": "tests/" }
}
}
Key Points
- Namespace prefix → directory mapping
vendor/autoload.phpregisters the loader--optimize/-obuilds a classmap for production--classmap-authoritativeskips filesystem fallback entirely
More most-asked PHP 8 questions
- What are the most important features introduced in PHP 8.0?
- What happens to an HTTP request in a PHP-FPM application, and what does 'shared nothing' mean?
- How should passwords be stored in PHP?
- What are named arguments and what are their benefits and risks?
- What is constructor property promotion?
- How does `match` differ from `switch`?
- What are union types in PHP 8 and how do you use them?
- What are enums in PHP 8.1? Explain pure vs backed enums.