Articles and classified ads

Exercise 6 of 9 in chapter 2 · 150 XP · 5 objectives checked by tests

Topics covered: InterfaceimplementsPolymorphism

Madame Lou has an old postwoman's bike to sell, and she is not the only one: classified ads are piling up at the post office. An ad is not an article: no author, no standfirst, but a price and a contact. And yet the front page has to show both, without wondering which is which.

Your mission

  1. Declare an interface Publication, with a single method: versHtml(): string (toHtml).
  2. Article implements Publication: the body of afficherArticle() becomes its versHtml() method, and the function goes away.
  3. Declare an Annonce class (classified ad) that implements Publication, with read-only string $titre, int $prix and string $contact. Its versHtml() method returns an <article class="annonce"> with the label <p class="rubrique">CLASSIFIED AD</p>, the title (escaped) in an <h2>, <p class="prix">€40</p> and <p class="contact">Contact: …</p>.
  4. Put the articles and the ad “Postwoman's bike for sale, very good condition”, €40, contact “Madame Lou, at the post office”, in a $publications array, and display them with $publication->versHtml().

Reminder

An interface is a contract: every class that implements it promises to have its methods. The loop no longer needs to know whether it holds an article or an ad: all it needs to know is that it's a Publication. That is polymorphism: the same call, different behaviors depending on the object.

If one day you do need to know what you're dealing with, instanceof tells you: $publication instanceof Annonce is true for an ad. Prefer the interface whenever you can: with it, a new kind of publication shows up without touching the loop.