My first autoloader

Exercise 3 of 4 in chapter 3 · 100 XP · 4 objectives checked by tests

Topics covered: Autoloadspl_autoload_register()Anonymous function

Seven require_once lines, in an order you must respect, and one slip is enough to break everything: Gaston knows all about it. Yet every file follows the same rule, the Article class in src/Article.php. And a rule is something PHP can learn.

Your mission

  1. Register an autoloader with spl_autoload_register(): a function that receives the name of an unknown class and loads the file in src/ that has that name.
  2. Delete the require_once lines of the classes: the autoloader replaces them all.
  3. Check that the front page still shows. The tests will even add a brand-new class to src/, to see whether it loads without anyone asking.

Reminder

When PHP meets a class it does not know, it calls, before giving up, the functions registered with spl_autoload_register(). That is autoload: a class is only loaded if you use it, and the order no longer matters. The function passed here has no name: it is an anonymous function, written directly in place of the argument: function (string $classe): void { … } ($classe is the class name). void announces that it returns nothing. We will come back to anonymous functions in detail in chapter 5.