PHP and autoload a basic concept

RemySd
2 min readNov 3, 2023

--

When we start to learn PHP, many concepts are skimmed. I think, the autoloader of PHP is one of these! So when we start to use composer with a framework like Laravel or Symfony, we skip this concept.

A quick refresh about it should be welcome!

Here two files, shorts as possible:

index.php

<?php

spl_autoload_register(function ($className) {
include $className . '.php';
});

$test = new TestClass();

TestClass.php

<?php

class TestClass {
}

Look at the index.php, the spl_autoload_register function is native by PHP. The goal is to include many files without to write all include manually. When we try to create a new instance of TestClass, PHP need to load first the class before to use it. Without autoload, we can use a simple include with the path of the file, and it’s works but this is redundant. This is at this moment than the autoload come!

At the moment where we try to use a class like the new TestClass(); PHP will try to load the class but if we never include it, that should occur an error but not if we use the autoload correctly. PHP is cool and let you a last chance to load the file required, and this last is the autoload. PHP call the spl_autoload_register function and give you the class name that he try to load. With this informations you can include the class at this moment. This same process is repeat for all class you try to load.

This story is focus on the autoload concept but currently it is normalized with a standard called PSR-4 and highly used by dev and framework in this modern world.

--

--