0
0
PHPprogramming~30 mins

Manual includes vs autoloading in PHP - Hands-On Comparison

Choose your learning style9 modes available
Manual includes vs autoloading in PHP
📖 Scenario: You are building a simple PHP project with multiple classes. You want to understand the difference between manually including class files and using autoloading to load classes automatically.
🎯 Goal: Create a PHP script that first uses manual include statements to load class files, then refactor it to use an autoloader function. You will see how autoloading simplifies your code.
📋 What You'll Learn
Create two PHP class files with exact class names and methods
Manually include these class files in a main script
Create an autoloader function using spl_autoload_register
Use the autoloader to instantiate classes without manual includes
Print messages from class methods to show successful loading
💡 Why This Matters
🌍 Real World
In real PHP projects, autoloading helps manage many class files without writing many include statements. It keeps code clean and easier to maintain.
💼 Career
Understanding autoloading is essential for PHP developers working on modern applications and frameworks like Laravel or Symfony.
Progress0 / 4 steps
1
Create two PHP class files
Create two PHP files named Car.php and Bike.php. In Car.php, define a class Car with a method drive() that returns the string "Car is driving". In Bike.php, define a class Bike with a method ride() that returns the string "Bike is riding".
PHP
Need a hint?

Each class should be in its own file named exactly Car.php and Bike.php.

2
Manually include class files in main script
Create a PHP file named index.php. Use include statements to include Car.php and Bike.php. Then create objects $car of class Car and $bike of class Bike.
PHP
Need a hint?

Use include 'Car.php'; and include 'Bike.php'; at the top of index.php.

3
Add autoloader function to load classes automatically
In index.php, remove the manual include statements. Instead, add an autoloader function using spl_autoload_register that loads class files by appending .php to the class name. Then create objects $car and $bike as before.
PHP
Need a hint?

The autoloader function should include the file named after the class with .php extension.

4
Print messages from class methods to show loading works
In index.php, add echo statements to print the results of $car->drive() and $bike->ride() on separate lines.
PHP
Need a hint?

Use echo $car->drive() . "\n"; and echo $bike->ride() . "\n"; to print messages.