Chapter 3 of the Learn PHP 8 from scratch track
Too many requires
4 exercises · 500 XP · about 1 h 30 min
require_once__DIR__Code organizationDebuggingError messageLoading orderAutoloadspl_autoload_register()Anonymous functionNamespacesnamespaceuse
The chapter's exercises
-
One file per class
Exercise 1 · 100 XP · 5 objectives checked by tests
public/index.php is now more than 150 lines long, and Madame Lou gets lost in it. To find the Annonce class, she has to scroll through the whole page. In a PHP project, each class has its own file, kept in src/.
require_once__DIR__Code organization
-
Class not found
Exercise 2 · 150 XP · 4 objectives checked by tests
Gaston wanted to help. He wrote a Bulletin class (weather report) for his forecast, and while he was at it, he “tidied up” the require_once lines in order of importance. The result: the gazette shows an error instead of the front page, and Madame Lou can't make head or tail of it.
DebuggingError messageLoading order
-
My first autoloader
Exercise 3 · 100 XP · 4 objectives checked by tests
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.
Autoloadspl_autoload_register()Anonymous function
-
Namespaces
Exercise 4 · 150 XP · 5 objectives checked by tests
Odette's nephew wants to add a little module he found on the Internet to the site. The trouble is, it has an Article class of its own. Two classes with the same name, and PHP refuses to choose. Real projects file their classes under a namespace, like a family name.
NamespacesnamespaceuseAutoload