PHP $this
Summary: in this tutorial, you will learn about PHP $this
keyword and how to use $this
inside a class to reference the current object.
What is $this in PHP?
In PHP, $this
keyword references the current object of the class. The $this
keyword allows you to access the properties and methods of the current object within the class using the object operator (->
):
$this->property
$this->method()
Code language: PHP (php)
The $this
keyword is only available within a class. It doesn’t exist outside of the class. If you attempt to use the $this
outside of a class, you’ll get an error.
When you access an object property using the $this
keyword, you use the $
with the this
keyword only. And you don’t use the $
with the property name. For example:
$this->balance
Code language: PHP (php)
The following shows the BankAccount
class:
class BankAccount
{
public $accountNumber;
public $balance;
public function deposit($amount)
{
if ($amount > 0) {
$this->balance += $amount;
}
}
public function withdraw($amount)
{
if ($amount <= $this->balance) {
$this->balance -= $amount;
return true;
}
return false;
}
}
Code language: HTML, XML (xml)
In this example, we access the balance
property via the $this
keyword inside the deposit()
and withdraw()
methods.
Chaining methods
First, create a new BankAccount
object:
// create a new account object
$account = new BankAccount();$account->accountNumber = 1;
$account->balance = 100;
Code language: PHP (php)
Second, call the deposit()
method three times to deposit different amounts of money:
$account->deposit(100);
$account->deposit(200);
$account->deposit(300);
Code language: PHP (php)
This code is quite verbose. It would be more concise and expressive if you can write these statements using a single statement like this:
$account->deposit(100)
->deposit(200)
->deposit(300);
Code language: PHP (php)
This technique is called method chaining. To form the method chaining, the deposit()
method needs to return a BankAccount
object, which is the $this
inside the BankAccount
class like this:
public function deposit($amount)
{
if ($amount > 0) {
$this->balance += $amount;
}
return $this;
}
Code language: PHP (php)
The deposit()
returns the $this
which is the current object of the BankAccount
class. Therefore, you can call any public method of the BankAccount
class.
The following example calls the deposit()
method first and then the withdraw()
method in a single statement:
$account->deposit(100)
->withdraw(150);
Code language: PHP (php)
It’s equivalent to the following:
$account->deposit(100);
$account->withdraw(150);
Code language: PHP (php)
Summary
- PHP
$this
keyword references the current object of the class. It’s only available within the class. - Do use the method chaining by returning
$this
from a method to make the code more concise.