Which of the following best explains why autoloading is needed in PHP?
Think about how PHP finds and uses class definitions without manually including files.
Autoloading allows PHP to load class files automatically when a class is used, so you don't have to write many include or require statements. This makes code cleaner and can improve performance by loading only what is needed.
Given the following PHP code with an autoloader, what will be the output?
<?php spl_autoload_register(function ($class) { include $class . '.php'; }); $obj = new Car(); $obj->drive(); ?> // File Car.php contains: // <?php // class Car { // public function drive() { // echo "Driving"; // } // }
Check how the autoloader includes the class file and what the drive() method does.
The autoloader includes the Car.php file when the Car class is first used. Then the drive() method prints 'Driving'.
What error will this PHP code produce if the Car class file is not included and no autoloader is set?
<?php
$obj = new Car();
$obj->drive();
?>Think about what happens when PHP tries to create an object of a class that is not defined or loaded.
Without including the class file or autoloading, PHP cannot find the Car class and throws a fatal error.
Which statement best describes how autoloading helps organize PHP code?
Consider how autoloading relates to file structure and manual includes.
Autoloading lets you keep each class in its own file and loads it only when the class is used, so you don't need to include all files manually. This keeps the project clean and easier to maintain.
Given this autoloader function, what will happen if you try to create an object of class 'Bike' but the file 'Bike.php' does not exist?
<?php spl_autoload_register(function ($class) { include $class . '.php'; }); $obj = new Bike();
Think about what happens when include fails and then PHP tries to instantiate a missing class.
When include fails to find 'Bike.php', PHP issues a warning but continues. Then it tries to create a Bike object, which is undefined, causing a fatal error.