The $this keyword
The $this keyword is used to get the class's own properties and method inside the class.
<?php
class Car {
// The properties
public $comp;
public $color = "beige";
public $hasSunRoof = true;
// The method hello
public function hello()
{
return "Beep I am a <i>" . $this->comp . "</i>, and I ama <i> " . $this->color;
}
}
// Create the objects
$bmw = new Car();
$mercedes = new Car();
// Set the properties
$bmw->comp = "BMW";
$bmw->color = "blue";
$mercedes->comp = "Mercedes";
$mercedes->color = "green";
// Call method hello
echo $bmw->hello();
echo $mercedes->hello();
Let us create a User class using the same approach above and practice what we have learned in Chapter 2.
<?php
class User {
// The properties
public $firstName;
public $lastName;
// A method called hello
public function hello()
{
return "Hello " . $this->firstName . " " . $this->lastName;
}
}
$user1 = new User();
// Set the properties
$user1->firstName = 'Joe';
$user1->lastName = 'Doe';
// Function hello()
echo $user1->hello();
We can create any number of classes like this. Let us create one more class to understand how $this works.
<?php
class Animal {
// Class properties
public $type;
public $name;
public $breed;
// Class methods
function createAnimal($type, $name, $breed) {
$this->type = $type;
$this->name = $name;
$this->breed = $breed;
}
}
$daisy = new Animal();
$daisy->type = "dog";
$daisy->name = "Daisy";
$daisy->breed = "pomerenian";
printf("<p>The %s named %s is a %s.</p>", $daisy->type, $daisy->name, $daisy->breed);
Method Chaining
The $this keyword is also used for method and property chaining. Let us write some code to understand about method and property chaining using $this keyword.
<?php
class Car {
public $tank;
public function fill($float)
{
$this->tank = $float;
return $this;
}
public function ride($float)
{
$miles = $float;
$gallons = $miles / 50;
$this->tank -= $gallons;
return $this;
}
}
$bmw = new Car();
$tank = $bmw->fill(10)->ride(40)->tank;
echo "The number of gallons left is " . $tank . " gals";
Let us create a User class that uses method chaining using similar as above.
<?php
class User {
// Properties of the class
public $firstName;
public $lastName;
// Method to say hello
public function hello()
{
return "Hello, " . $this->firstName . " " . $this->lastName;
}
// Method to register
public function register()
{
echo $this->firstName . " " . $this->lastName . " is registered. ";
return $this;
}
// Method to send email
public function mail()
{
echo "Emailed";
}
}
$user1 = new User();
$user1->firstName = "Jon";
$user1->lastName = "Doe";
$user1->register()->mail();