PracticeType hinting for interfaces

Let's practice what we have just learned

* Press on the "solution button" to see our suggested solution.

What does it mean "program to an interface"?

  • A Make your classes and functions dependent on an interface.
  • B Make your classes and functions dependent on a concrete classes.
Solution:

Scratchpad to practice your coding *This will not be saved nor submitted to us.*

<?php
//Your practice code

In this tutorial we used an example for type hinting with interface in the form of abstract class. Now, we are going to practice what we have learned with type hinting to interface per se.

Create a User interface with set and get methods for both a $username property, as well as for a $gender property.

Solution:

Scratchpad to practice your coding *This will not be saved nor submitted to us.*

<?php
//Your practice code

Now, create a Commentator class to implement the User interface. Which methods should you write to implement the interface?

Solution:

Scratchpad to practice your coding *This will not be saved nor submitted to us.*

<?php
//Your practice code

Write a function to add "Mr." or "Mrs." to the username. The function should receive only objects that belong to the type User, so make sure to type hint it correctly.

Solution:

Scratchpad to practice your coding *This will not be saved nor submitted to us.*

<?php
//Your practice code

Run the code against a user with the name of "Jane" and against another user with the name of "Bob".

Expected result:
Mrs. Jane
Mr. Bob

Solution:

Scratchpad to practice your coding *This will not be saved nor submitted to us.*

<?php
//Your practice code
comments powered by Disqus