Type hinting for interfaces
In the "Type hinting for interfaces" tutorial, we learned about the benefits of type hinting for interfaces. Now, we are ready to implement what we learned by writing our own code which uses type hinting for interfaces.
In the "Type hinting for interfaces" tutorial, we learned about the benefits of type hinting for interfaces. Now, we are ready to implement what we learned by writing our own code which uses type hinting for interfaces.
* Press on the "solution button" to see our suggested solution.
What does it mean "program to an interface"?
A When you program to an interface you make your classes and functions dependent on an interface and not on concrete classes. It makes your code more flexible and ready for changes.
Scratchpad to practice your coding *This will not be saved nor submitted to us.*
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.
Scratchpad to practice your coding *This will not be saved nor submitted to us.*
Now, create a Commentator class to implement the User interface. Which methods should you write to implement the interface?
Scratchpad to practice your coding *This will not be saved nor submitted to us.*
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.
Scratchpad to practice your coding *This will not be saved nor submitted to us.*
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
Scratchpad to practice your coding *This will not be saved nor submitted to us.*
If so, the eBook"The essentials of object oriented PHP" can further help you.
"The essentials..." is an in-depth guide to help you quickly and easily increase your productivity and become a hot commodity in the job market.
Don't waste time!
Click on the green button to buy the eBook and start achieving your potential today!