Challenge: Abstract Classes and Methods

Try to create an abstract class and make the child classes inherit from that abstract class.

We'll cover the following


  • Create an abstract class named User with an abstract method named stateYourRole().
  • Add a protected property named $username to the User abstract class. Then, add the public setter and getter methods to set and get the $username.
  • Create an Admin class that inherits the abstract User class. Define the stateYourRole() method in the child class and make it return the string admin.
  • Create another class named Viewer that inherits the User abstract class. Define the methods that should be defined in each child class of the User class.
  • Inside the test() method, create an object from the Admin class. Set the $username to Balthazar and make it return the string admin by calling the appropriate method.

Coding exercise

Since these problems are designed for your practice, try to solve them yourself first. If you get stuck, you can click the “Show Solution” button to see how the problem can be solved. Good luck!

Get hands-on with 1200+ tech skills courses.