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 now add some methods to represent register and mail functionality to the User class that we had written in the previous tutorials. These methods would echo a string as placeholder for their actual purpose.

This is the User class that we have generated in the previous tutorial.

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

Add a register() method to the class that echoes the name of the user plus the verb "registered".
Use the $this keyword to approach the class's properties.

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 "emailed".

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 that 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

Create a new $user1 object with the first name of "Jane" and the last name of "Roe".
For this object, chain the mail() method to the register() method and see the result.

Expected result:
Jane Roe rgistered emailed

Solution:

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

<?php
//Your practice code

Notice that each method we want to chain to should return the $this keyword. So, if we would like to write the next line of code that chains together 3 methods:

$user1 -> register() -> mail() -> hello();

We would have to return the $this keyword from both the register() and mail() methods, but we won't have to return the $this keyword from the hello() method because it concludes the chain.

comments powered by Disqus