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
- Declare an interface
Publication, with a single method:versHtml(): string(toHtml). ArticleimplementsPublication: the body ofafficherArticle()becomes itsversHtml()method, and the function goes away.- Declare an
Annonceclass (classified ad) that implementsPublication, with read-onlystring $titre,int $prixandstring $contact. ItsversHtml()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>. - Put the articles and the ad “Postwoman's bike for sale, very good condition”, €40, contact “Madame Lou, at the post office”, in a
$publicationsarray, 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.