PracticeChaining methods and properties

Practice: Chaining methods and properties

In the "Chaining methods and properties" tutorial, we learned how to chain properties and methods in order to make our code more readable.

Now, we can practice our newly acquired knowledge with the following series of questions that will guide us through the process of writing our own code which is based on the tutorial.

Let's practice what we have just learned

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

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

This is the User class that we are going to use for this excercise. The hello() method echoes the first name of the user.

class User {
 
  // The class properties.
  public $firstName;
 
  // A method that says hello to the user $firstName.
  // The user $firstName property can be approached with the $this keyword.
  public function hello()
  {
    echo "hello, " .  $this -> firstName;
  }
}

Add a register() method to the class that echoes the string " >> registered".

Solution:

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

<?php
//Your practice code

Add a mail() method to the class that echoes the string " >> email sent".

Solution:

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

<?php
//Your practice code

Add return $this to the hello() method so it can be chained to any other method in the class.

Solution:

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

<?php
//Your practice code

Add return $this to the register() method so it can also be chained.

Solution:

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

<?php
//Your practice code

Create a new $user1 object with the first name of "Jane".
For this object, chain the methods in the following order: hello() -> register() -> mail()

Expected result:
hello, Jane >> registered >> email sent

Solution:

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

<?php
//Your practice code

Note that each method we want to chain to should return the $this keyword in order to not break the chain. So, the hello() and register() methods have to return the $this keyword, but there is no need to return $this from the mail() method since it ends the chain.

comments powered by Disqus