PracticeThe $this keyword

Practice: The $this keyword

The "$this keyword" tutorial taught us that we need to use the $this keyword in order to approach the class's own properties and methods from within the class.

In this practice section, we can further our understanding of the $this keyword by writing our own code which is based on the material that we learned in the tutorial.

Let's practice what we have just learned

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

Which keyword would you use in order to approach the class properties and methods from within the class?

  • A The new keyword.
  • B The class keyword.
  • C The $this keyword.
Solution:

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

<?php
//Your practice code

Coding exercise

In the previous tutorial, we wrote the hello() method inside the User class. In the following exercise, we will add to the hello() method the ability to approach the class properties with the $this keyword.

First, let's remind ourselves what the User class looks like:

class User {
 
  // The class properties.
  public $firstName;
 
  public $lastName;
 
  // A method that says hello to the user.
  public function hello()
  {
    return "hello";
  }
}

Wouldn't it be nicer if we could allow the hello() method the ability to get the class's properties, so that it would be able to say hello to the user name (for example, "hello, John Doe")?

Add to the hello() method the ability to approach the $firstName property, so the hello() method would be able to return the string "hello, $firstName".

Solution:

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

<?php
//Your practice code

Create a new object with the first name of "Jonnie" and last name of "Roe".

Solution:

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

<?php
//Your practice code

Echo the hello() method for the $user1 object, and see the result.

Expected result:
hello, Jonnie

Solution:

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

<?php
//Your practice code
comments powered by Disqus