What is Autoloading Classes in PHP

What is Autoloading Classes in PHP

If you are here, then I can assume you have been working on PHP for a good amount of time then you know autoloading classes in PHP. PHP is an object-oriented program that uses classes to make programming more comfortable and less repetitive. 

Sometimes you put a class on one file that is needed in another file, then you might use something like require(), require_once(), include(), or include_once(). This is a very common practice in PHP, as we as developers usually create multiple files for each class and then use those commands to add them to the base file. 

What if you don’t have to do that? What if you could autoload all those classes scattered through your files and autoload them each time you needed them in the base file? Here’s where autoloading comes in to save you from all those hustles. 

Prerequisite for Autoloading

You can’t just start putting the Autoloading command in your PHP code, before starting this feature you have to follow some rules, 

  1. You must create a different file for different functions in your code. 
  2.  Also, to make autoloader work perfectly in the system, you have to make sure that the class name inside your file and the filename are the same. 

For example, if you create a class named “animals,” then you should name the file “animals.php.”

What are Autoloading classes in PHP?

I think when I say the name “Autoloading,” you might understand the functionality of this a bit. It must load something automatically, i.e., without writing extra code. So, what are autoloading classes in PHP?

Autoloader loads classes that are written in different files throughout your file. Well, require(), include_once(), and some other functions also do the same thing; what is the difference? 

In a real-world project, it is common to use a lot of files for different classes, and when you use require() or some other stuff, all the files that you put in the list must load when you try to use the main file. The code using require() or some other function will look like this.

 <?php
require 'filename.php';
include 'filename.php';
include_once 'filename.php';
?>Code language: PHP (php)

This is a problem, as loading unnecessary files can affect the speed of your websites and take too much time during the loading process. Besides, when some other developer tries to work on your project, it will become a tedious task for him as the code will be bloated. 

On the other hand, the autoloader will take the filename of your class file as an argument. Now, when you are working with hundreds of files, you don’t have to write hundreds of codes just to run the program. 

The autoloader will simply find the desired class file and load it when it is necessary. The developers who worked on the projects for a long time claimed that switching to an autoloading function made their website 10 times faster than before. So, you understand why you should learn Autoloader ASAP. 

Autoloading Before PHP 8.0(PHP 7.2 or Before)

Back in the day, there was a function called __autoload() that was used to autoload a bunch of classes so they would load when necessary. You could use __autoload() using this method:

__autoload(string <code>$class</code>): voidCode language: PHP (php)

Note: The code is taken from PHP official documentation

But in PHP 7.2, the __autoload() function, which was an alternative to spl_autoload_register(), was deprecated, and in PHP 8.0, it was completely removed. __autoload() was removed because it was not flexible enough to use. 

New Autoloading Method

As __autoloading() is not available for us anymore, what should you use to autoload everything? Well, the function we will discuss is not something new, it has been available in PHP since 5.1.2. The spl_autoloading_register()

Let us consider a scenario where you have three files that contain different classes, and as we have mentioned before, the name of the class and the file name containing the class are the same. In our case, the file names are class1.php, class2.php, class3.php, and class4.php 

If you followed the traditional method the inclusion of those classes in the main file should look like this.

 <?php 
require 'class1.php'; 
include 'class2.php'; 
include_once 'class3.php';
require_once 'class4.php'; 
?>Code language: PHP (php)

But when you use spl_autoloading_register(), then the code will look like this. Assuming all the files are in the root folder.

<?php
spl_autoload_register(function ($class_name) {
    include $class_name . '.php';
});

$obj  = new MyClass1();
$obj2 = new MyClass2(); 
?> Code language: PHP (php)

Note: The code is taken from PHP official documentation

Notice both of these codes. Now imagine the file containing classes is more than 100; then, writing the code using the previous method will not only be tedious but also create a huge chance for mistakes. The spl_autoloading_register() method can easily solve the issue. 

What Happens When You Autoload

You have followed everything that you need for autoloading in PHP. Now, what happens when the code starts working? 

Registering

Like many user-friendly languages, PHP also has many built-in functions that are helpful to get a job done where you would have to spend time and figure out the concept yourself. The spl_autoloading_register() function is one of PHP’s built-in functions. 

When you execute spl_autoloading_register(), the first thing that happens is an anonymous function callback for the autoloading function, but you call that function at different times, and PHP remembers all those callbacks. This frequent callback is known as “registering.” 

Running

Whenever you try to access one class, PHP searches that class to see if it is available. Autoloading then continues the finding process and keeps searching for that class among the registered autoloaders. 

Termination 

If something is found, the autoloader will call that class; otherwise, it will terminate the process and stop the program. 

Autoloading on Namespace Structure

In the previous example, we used an autoloading function to activate autoloading; however, what if I told you that you don’t need a function to activate autoloading? Here is a scenario and how you could use that namespace structure. 

Say you have two folders that are “class” and “loop,” and inside the class folder you have a home.php file and inside the loop folder, you have a loop.php. 

Now, inside both files, we will add some class

class/home.php

<?php
namespace class;
class home {
 public function get(){
  return 'class/home.php';
 }
}Code language: PHP (php)

loop/loop.php

<?php
namespace loop;
class loop {
public function get(){
return 'loop/loop.php';
}
}Code language: HTML, XML (xml)

And on the file where we will load the code, we will write it like this:

<?php

spl_autoload_register();
$home = new class\home();
echo $home->get() . <br>;

$home = new loop\loop();
echo $loop->get()
?>Code language: PHP (php)

Exception Handling With Autoloading

Sometimes when you call a class file using the autoloader, there is a chance that the file might not be there at all. Maybe you forgot to write the function properly or something similar error has happened. Now, how do you use exceptions in PHP autoloader? Let us look at a code example.

<?php
spl_autoload_register(function($className) {
   $file = $className . '.php';
   if (file_exists($file)) {
      echo "$file included
";
      include $file;
   } else {
      throw new Exception("Unable to load $className.");
   }
});
try {
   $obj1 = new test1();
   $obj2 = new test10();
} catch (Exception $e) {
   echo $e->getMessage(), "
";
}
?>Code language: PHP (php)

Conclusion 

As a programmer, your first job is to take care of bloat and make your code easy to load and fast. If you are working in PHP, the autoloader function can do that. Autoloader has made writing PHP easy and free of error. This is why you should immediately learn about autoloaders. 

Sharing is caring

Did you like what S.M. SHAFAKATUL ISLAM wrote? Thank them for their work by sharing it on social media.

0/10000

No comments so far

Curious about this topic? Continue your journey with these coding courses: