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 SedanWhen 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 SUVKey Point: $this always refers to the specific object that called the method. Each object gets its own context when a method runs.
Challenge
EasyComplete 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 theCarclass definition where you'll add thedisplayInfomethoddriver.php: Main execution file that imports and uses theCarclass (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 SedanWhen 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();
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe $this KeywordMethodsPropertiesConstructor (__construct)Destructor (__destruct)Recap - Simple Calculator4Inheritance
Basic InheritanceThe parent:: KeywordMethod OverridingThe final KeywordAbstract ClassesRecap - Employee Hierarchy7Encapsulation
Public, Protected, PrivateAccess Modifiers in DepthGetters and SettersInformation HidingConstructor Promotion (8.0)Recap - Student Records System2Namespaces & Autoloading
Introduction to NamespacesThe use KeywordPSR-4 Autoloading StandardComposer AutoloaderRecap - Organized Project5Interfaces & Contracts
Introduction to InterfacesImplementing InterfacesMultiple Interface ImplementInterface vs Abstract ClassType Hinting with InterfacesRecap - Shape Calculator8Magic Methods
Magic Methods Introduction__toString & __debugInfo__get, __set, __isset, __unset__call & __callStatic__clone & Object Cloning__serialize & __unserializeRecap - Custom Collection11Type System & Error Handling
Type DeclarationsNullable TypesUnion & Intersection TypesException ClassesCustom Exception HierarchyTry, Catch, FinallyRecap - Form Validator14Project: Library Management
Project OverviewBook and User Classes3Class Properties
Instance vs Static PropertiesConstants in ClassesStatic Methods & PropertiesPrivate & Protected PropertiesReadonly Properties (PHP 8.1)Recap - Bank Account Manager6Polymorphism
Method Overriding RevisitedPolymorphism via InterfacesType Hinting & Union TypesLate Static BindingRecap - Payment Processor9Traits
Introduction to TraitsUsing Multiple TraitsTrait Conflict ResolutionAbstract Methods in TraitsTraits vs Inheritance12Design Patterns Part 1
Intro to Design PatternsSingleton PatternFactory PatternObserver PatternStrategy Pattern