The $this Keyword

JA JASWANT Updated 19 Oct 2026
6 min read ·Lesson 124 of 143
In this post

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

  1. When $pageViews->increment() runs, $this refers to $pageViews, so $this->count++ changes its counter.
  2. When $downloads->increment() runs, $this refers to $downloads.
  3. 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(), and tax() calls $this->subtotal(). Methods build on each other through $this.
  • The arrow function inside subtotal() can use $this->lines because 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 static means "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

KeywordRefers ToUsed For
$thisThe current objectInstance properties and methods: $this->name, $this->save()
selfThe class where the code is writtenConstants and static members: self::MAX_ITEMS, self::create()
staticThe 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 static as the return type for fluent methods that return $this.
  • Pass $this to collaborators when they need to work with the current object.
  • Mark closures static when 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

0 Comments

Reviewed before they appear

No comments yet.

PHP
PHP Home PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement PHP Home PHP Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope PHP Casting Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence Continue Statement Modify Strings PHP If...Else...Elseif PHP If Modify Strings PHP If Operators PHP Functions Concatenate Strings PHP If...Else Slicing Strings User-defined Functions Slicing Strings PHP Shorthand if Escape Characters Default Argument Values PHP Nested if Pass by Reference String Interpolation Named Arguments PHP File Upload Variadic Functions Return Values Search in Strings Multibyte Strings Type Declarations in Functions PHP Numbers PHP Math PHP Floats PHP Random Numbers PHP Constants PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Cookies PHP Destructor PHP Access Modifiers Readonly Properties PHP Sessions PHP Inheritance Method Overriding PHP Filters The final Keyword CSRF Protection PHP Filters Advanced Session Security Secure Cookies PHP Magic Constants File Upload Security PHP Callback Functions PHP Operators Filesystem Security PHP JSON Arithmetic Operators Error Reporting in Production Hiding PHP Assignment Operators PHP Configuration (php.ini) Comparison Operators PHP Command Line (CLI) PHP Exceptions Increment / Decrement Operators Migrating to PHP 8 PHP Form Validation PHP Form Required PHP Form URL/E-mail Error Handling Form Input Sanitizing Escaping Output (htmlspecialchars) Custom Error Handler Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll AJAX with JSON Security Introduction Password Hashing SQL Injection Prevention XSS Prevention Garbage Collection Project: Simple Blog PHP What is OOP PHP Classes/Objects The $this Keyword Access Array Items Update Array Items Add Array Items Remove Array Items Sorting Arrays Multidimensional Arrays Array Destructuring Array Spread Operator Search in Arrays Merge Arrays PHP Abstract Classes PHP Interfaces Polymorphism PHP Traits PHP Static Methods PHP Static Properties Late Static Binding Magic Methods Object Cloning
Ask about this post
AI Ask about this post

Ask questions about The $this Keyword and get answers drawn from it.

Signed-in readers only.