The $this Keyword
What Is $this ? In simple terms: Inside a class, $this means "the object I am currently working on". When you call $pen->priceWithTax() , inside that method $this is $pen . When you call the same m
What Is $this?
In simple terms: Inside a class, $this means "the object I am currently working on". When you call $pen->priceWithTax(), inside that method $this is $pen. When you call the same method on $lamp, $this is $lamp.
Technically: $this is a special, read-only variable that PHP automatically makes available inside non-static methods. It holds a reference (handle) to the object on which the method was called. It is used to access the object's properties ($this->name) and to call its other methods ($this->validate()).
Why It Is Needed
A class is written once, but used for many objects. The method code needs a way to refer to "the current object's data" without knowing which object that will be. $this provides exactly that.
Using $this to Access Properties
<?php
class Counter
{
private int $count = 0;
public function increment(): void
{
$this->count++;
}
public function value(): int
{
return $this->count;
}
}
$pageViews = new Counter();
$downloads = new Counter();
$pageViews->increment();
$pageViews->increment();
$downloads->increment();
echo "Page views: " . $pageViews->value() . "\n";
echo "Downloads: " . $downloads->value() . "\n";
Output
Page views: 2
Downloads: 1
How It Works
- When
$pageViews->increment()runs,$thisrefers to$pageViews, so$this->count++changes its counter. - When
$downloads->increment()runs,$thisrefers to$downloads. - The same method code serves both objects, each with its own data.
$this->count vs $count
Inside a method, $count (without $this->) is an ordinary local variable of the method — unrelated to the property:
<?php
class Counter
{
private int $count = 0;
public function brokenIncrement(): void
{
$count = 10; // local variable: the property is unchanged
}
public function value(): int
{
return $this->count;
}
}
$counter = new Counter();
$counter->brokenIncrement();
echo $counter->value() . "\n";
Output
0
Forgetting $this-> is one of the most common OOP mistakes for beginners, especially those coming from languages such as Java, where the object reference can often be omitted.
Calling Other Methods With $this
<?php
class Invoice
{
private array $lines = [];
public function addLine(string $item, int $quantity, float $price): void
{
$this->lines[] = ['item' => $item, 'quantity' => $quantity, 'price' => $price];
}
public function subtotal(): float
{
return array_sum(array_map(fn(array $line): float => $line['quantity'] * $line['price'], $this->lines));
}
public function tax(): float
{
return round($this->subtotal() * 0.18, 2);
}
public function total(): float
{
return $this->subtotal() + $this->tax();
}
}
$invoice = new Invoice();
$invoice->addLine('Notebook', 3, 60);
$invoice->addLine('Gel Pen', 10, 20);
printf("Subtotal: ₹%.2f\nGST: ₹%.2f\nTotal: ₹%.2f\n", $invoice->subtotal(), $invoice->tax(), $invoice->total());
Output
Subtotal: ₹380.00
GST: ₹68.40
Total: ₹448.40
total()calls$this->subtotal()and$this->tax(), andtax()calls$this->subtotal(). Methods build on each other through$this.- The arrow function inside
subtotal()can use$this->linesbecause closures created inside a method are automatically bound to the object.
Returning $this: Method Chaining
A method that returns $this lets callers chain several calls in one expression — a fluent interface:
<?php
class EmailBuilder
{
private array $recipients = [];
private string $subject = '';
private string $body = '';
public function to(string $email): static
{
$this->recipients[] = $email;
return $this;
}
public function subject(string $subject): static
{
$this->subject = $subject;
return $this;
}
public function body(string $body): static
{
$this->body = $body;
return $this;
}
public function build(): string
{
return 'To: ' . implode(', ', $this->recipients) . "\n"
. "Subject: {$this->subject}\n\n"
. $this->body;
}
}
echo (new EmailBuilder())
->to('asha@example.com')
->to('bala@example.com')
->subject('Class schedule')
->body('The PHP class starts at 7 PM.')
->build() . "\n";
Output
To: asha@example.com, bala@example.com
Subject: Class schedule
The PHP class starts at 7 PM.
How It Works
- Each setter changes the object and returns
$this— the same object — so the next method can be called on the result. - The return type
staticmeans "an instance of the class this method was called on", which keeps chaining correct in subclasses. - Query builders (
$query->where(...)->orderBy(...)->limit(...)) and many configuration APIs in frameworks use this style.
For immutable objects, "wither" methods return a modified copy instead of $this (for example, DateTimeImmutable::modify()); see Readonly Properties.
Passing $this to Other Objects
An object can pass itself to another object — for example, to notify a listener:
<?php
class OrderNotifier
{
public function orderPlaced(Order $order): void
{
echo "Notify warehouse: pack order #{$order->id} ({$order->itemCount()} items)\n";
}
}
class Order
{
private array $items = [];
public function __construct(public readonly int $id) {}
public function addItem(string $sku): void
{
$this->items[] = $sku;
}
public function itemCount(): int
{
return count($this->items);
}
public function place(OrderNotifier $notifier): void
{
$notifier->orderPlaced($this);
}
}
$order = new Order(501);
$order->addItem('PEN-01');
$order->addItem('NB-A5');
$order->place(new OrderNotifier());
Output
Notify warehouse: pack order #501 (2 items)
Inside place(), $this is the order being placed; the notifier receives it and can read its public data and call its public methods.
Where $this Is Not Available
Static Methods
Static methods belong to the class, not to an object, so there is no current object:
<?php
class Config
{
private array $values = ['app' => 'GoCourse'];
public static function appName(): string
{
return $this->values['app'];
}
}
try {
echo Config::appName();
} catch (Error $e) {
echo get_class($e) . ": " . $e->getMessage() . "\n";
}
Output
Error: Using $this when not in object context
Static methods use self:: or static:: to access static members instead (see PHP Static Methods).
Static Closures
Closures created inside a method are bound to $this automatically, unless they are declared static:
$format = static fn(float $price): string => '₹' . number_format($price, 2); // no $this inside
$this Cannot Be Reassigned
$this = new Order(2); // Fatal error: Cannot re-assign $this
$this always refers to the object the method was called on; it cannot be replaced.
$this, self, and static
| Keyword | Refers To | Used For |
|---|---|---|
$this | The current object | Instance properties and methods: $this->name, $this->save() |
self | The class where the code is written | Constants and static members: self::MAX_ITEMS, self::create() |
static | The class the method was called on (late static binding) | Static members that subclasses may override; return types for fluent methods |
These are covered further in PHP Class Constants, PHP Static Methods, and Late Static Binding.
Common Mistakes
Forgetting $this->
Effect: A local variable is used instead of the property; changes are lost.
Fix: Access properties with $this->property.
Writing $this->$property
Effect: The property name is taken from the value of $property (dynamic access).
Fix: Write $this->property without the second $, unless dynamic access is intended.
Using $this in Static Methods
Effect: Error: Using $this when not in object context.
Fix: Make the method non-static, or use static members.
Returning $this From Methods That Should Return Values
Effect: Callers get the object instead of the expected result.
Fix: Use fluent returns only for configuration-style methods; query methods should return their result.
Best Practices
- Always use
$this->for properties and methods of the current object. - Use
staticas the return type for fluent methods that return$this. - Pass
$thisto collaborators when they need to work with the current object. - Mark closures
staticwhen they do not use$this. - Keep methods that change state separate from methods that return information.
Official reference: https://www.php.net/manual/en/language.oop5.basic.php