Given the following PHP code that uses Composer's autoload, what will be the output?
require 'vendor/autoload.php'; use App\Utils\Greeting; $greet = new Greeting(); echo $greet->sayHello();
Assume the class App\Utils\Greeting is correctly defined in src/Utils/Greeting.php and Composer's autoload is configured with PSR-4 for the App\ namespace.
require 'vendor/autoload.php'; use App\Utils\Greeting; $greet = new Greeting(); echo $greet->sayHello();
Think about how Composer's autoload maps namespaces to file paths.
Composer's autoload uses PSR-4 to map the App\ namespace to the src/ directory. The class Greeting is found and loaded automatically, so the method sayHello() runs and outputs the greeting.
Composer generates a file that handles autoloading of classes based on your composer.json configuration. What is the name and location of this file?
Look inside the vendor directory after running composer install.
The file vendor/autoload.php is generated by Composer and is the main entry point to autoload all classes according to the configured autoload rules.
Consider this composer.json snippet:
{
"autoload": {
"psr-4": {
"App\\": "src/"
}
}
}And this PHP code:
require 'vendor/autoload.php'; use App\Controllers\HomeController; $controller = new HomeController();
The file src/Controllers/HomeController.php exists and defines the class App\Controllers\HomeController. However, running the code causes a Class not found error. What is the most likely cause?
Think about what Composer needs to do after adding new classes.
Composer generates autoload files when you run composer dump-autoload or composer install. If you add new class files without regenerating, the autoloader won't know about them, causing a class not found error.
What error will this PHP code produce?
require 'vendor/autoload.php' use App\Models\User; $user = new User();
Check the syntax carefully, especially punctuation.
The missing semicolon after the require statement causes a parse error at the next line where 'use' is found.
Given this composer.json autoload section:
{
"autoload": {
"psr-4": {
"Lib\\": "lib/",
"Lib\\Utils\\": "lib/Utils/"
}
}
}And the following files exist:
- lib/Helper.php (class Lib\Helper)
- lib/Utils/Parser.php (class Lib\Utils\Parser)
- lib/Utils/Formatter.php (class Lib\Utils\Formatter)
- lib/Utils/Extra/Tool.php (class Lib\Utils\Extra\Tool)
How many of these classes will be autoloaded correctly by Composer?
Remember how PSR-4 prefixes work and how they map to directories.
The prefix "Lib\\": "lib/" maps Lib\Helper to lib/Helper.php. The prefix "Lib\\Utils\\": "lib/Utils/" maps Lib\Utils\Parser to lib/Utils/Parser.php, Lib\Utils\Formatter to lib/Utils/Formatter.php, and Lib\Utils\Extra\Tool to lib/Utils/Extra/Tool.php because PSR-4 supports mapping the remaining namespace components to subdirectories. Thus, all 4 classes will be autoloaded correctly.