Namespaces

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

Topics covered: NamespacesnamespaceuseAutoload

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.

Your mission

  1. At the top of each file in src/, right after <?php, declare the namespace: namespace Gazette;. The Article class becomes Gazette\Article.
  2. In public/index.php, import the classes with use Gazette\Article; (and the same for Annonce, Auteur, Bulletin, Rubrique and Sommaire): the rest of the file does not change.
  3. The autoloader now receives Gazette\Article: make it remove the Gazette\ prefix to find src/Article.php again.

Reminder

A namespace prefixes classes, the way a folder prefixes a file: Gazette\Article and Module\Article can live side by side. use gives a short name to a class from another namespace. In a PHP string, the backslash is written twice: 'Gazette\\'. To remove the prefix, str_starts_with($classe, 'Gazette\\') tells you whether the name starts with it, strlen('Gazette\\') counts its characters, and substr($classe, 8) keeps what comes after the 8th character.