Menu
Coddy logo textTech

The $this Keyword

Part of the Object Oriented Programming section of Coddy's PHP journey — lesson 4 of 91.

The $this keyword refers to the current instance of a class within its methods. It allows you to access and modify properties of the current object.

Here is an example of a class with methods using $this:

<?php
class Car {
    public $color;
    public $model;

    public function honk() {
        echo "Beep beep!\n";
    }

    public function describe() {
        echo "I am a " . $this->color . " " . $this->model . "\n";
    }
}

The $this keyword is used inside methods to refer to the object that called the method.

Create a car object and set properties:

$myCar = new Car();
$myCar->color = "Red";
$myCar->model = "Sedan";

Now call the methods:

$myCar->honk();
$myCar->describe();

Output:

Beep beep!
I am a Red Sedan

When you call $myCar->describe(), PHP automatically sets $this to refer to $myCar. This is how the method knows which object's properties to access.

If you had another car object:

$otherCar = new Car();
$otherCar->color = "Blue";
$otherCar->model = "SUV";
$otherCar->describe(); // I am a Blue SUV

Key Point: $this always refers to the specific object that called the method. Each object gets its own context when a method runs.

challenge icon

Challenge

Easy

Complete the Car class in car.php by adding a method called displayInfo that uses the $this keyword to print the car's year, make, and model in the format:

"This car is a [year] [make] [model]"

  • car.php: Contains the Car class definition where you'll add the displayInfo method
  • driver.php: Main execution file that imports and uses the Car class (locked)

Cheat sheet

The $this keyword refers to the current instance of a class within its methods, allowing you to access and modify properties of the current object.

Using $this in a class:

<?php
class Car {
    public $color;
    public $model;

    public function describe() {
        echo "I am a " . $this->color . " " . $this->model . "\n";
    }
}

Creating an object and calling methods:

$myCar = new Car();
$myCar->color = "Red";
$myCar->model = "Sedan";
$myCar->describe(); // I am a Red Sedan

When you call $myCar->describe(), PHP automatically sets $this to refer to $myCar. Each object gets its own context when a method runs, so $this always refers to the specific object that called the method.

Try it yourself

<?php
require_once 'car.php';

$myCar = new Car();
$myCar->year = 2020;
$myCar->make = "Toyota";
$myCar->model = "Corolla";

$myCar->displayInfo();
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming