Challenge: Access Modifiers

Add a property to a class and write appropriate getter and setter functions.

We'll cover the following


Let’s consider a User class that contains a private property with the name of $firstName.

  • Create a setter method to set the $firstName property value. Remember to use the suitable access modifier (public/private).
  • Create a getter method to return the $firstName value.
  • Inside a test() method, create a new user object with the name of $user1, set its name using the setter method to Joe, and return its name from the test() method using the getter 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.