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".
class User {
// The class properties.
public $firstName;
public $lastName;
// A method that says hello to the user.
public function hello()
{
return "hello, " . $this -> firstName;
}
}
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".
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;
}
}
// Create a new object.
$user1 = new User();
// Set the user $firstName and $lastName properties.
$user1 -> firstName = "Jonnie";
$user1 -> lastName = "Roe";
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
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;
}
}
// Create a new object.
$user1 = new User();
// Set the user $firstName and $lastName properties.
$user1 -> firstName = "Jonnie";
$user1 -> lastName = "Roe";
// Echo the hello() method.
echo $user1 -> hello();
Scratchpad to practice your coding *This will not be saved nor submitted to us.*
<?php
//Your practice code