Challenge: Chaining Methods and Properties

Implement functions in a class so that they can be chained to any other function.

We'll cover the following

Task

Let’s add two methods to represent the register and mail functionalities in the User class. These methods will echo a string as a placeholder for their actual purpose.

The User class is given below. In this task, we’ll do the following:

  • Add a hello() method that echoes the user’s first name.
  • Add a register() method to the class that echoes the string >> registered.
  • Add a mail() method to the class that echoes the string >> email sent.
  • Add return $this; to the hello() method so it can be chained to any other method in the class.
  • Add return $this; to the register() method so it can also be chained.
  • Create a test() method with the $user1 object with its first name as Jane. For this object, chain the methods in the following order:
hello() -> register() -> mail()

Expected output

hello, Jane >> registered >> email sent

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 1400+ tech skills courses.