The $this Keyword

Ma Mahalakshmi V Updated 14 Nov 2026
6 min read ·Lesson 150 of 255

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 Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope Static Variables Variable Variables PHP Echo / Print PHP printf / sprintf PHP Data Types PHP Booleans PHP NULL PHP Strings String Functions Modify Strings Concatenate Strings Slicing Strings Escape Characters String Interpolation Heredoc and Nowdoc Search in Strings Multibyte Strings PHP Floats PHP Casting PHP Type Juggling PHP Math PHP Random Numbers PHP Constants PHP Magic Constants PHP Operators Arithmetic Operators Assignment Operators Comparison Operators Increment / Decrement Operators Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence PHP If...Else...Elseif PHP If PHP If Operators PHP If...Else PHP Shorthand if PHP Nested if PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement Continue Statement PHP Functions User-defined Functions Function Arguments Default Argument Values Pass by Reference Named Arguments Variadic Functions Return Values Type Declarations in Functions Recursive Functions Variable Functions Anonymous Functions Closures Arrow Functions First-class Callable Syntax PHP Arrays Indexed Arrays Associative Arrays Create Arrays 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 array_map / array_filter / array_reduce Array Functions PHP Superglobals $GLOBALS $_SERVER $_REQUEST $_POST $_GET $_FILES $_COOKIE $_SESSION \$\_ENV PHP RegEx RegEx Patterns RegEx Modifiers preg_match preg_replace preg_split PHP RegEx Functions PHP Form Handling PHP Form Validation PHP Form Required PHP Form URL/E-mail Form Input Sanitizing Escaping Output (htmlspecialchars) Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting DateTime Class Timezones PHP Include Include vs Require PHP File Handling PHP File Open/Read PHP File Create/Write File Delete / Rename / Copy PHP Directories PHP CSV Files PHP File Upload PHP Cookies PHP Sessions PHP Filters PHP Filters Advanced PHP Callback Functions PHP JSON PHP Exceptions Error Handling Custom Error Handler Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators PHP What is OOP PHP Classes/Objects The $this Keyword PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Destructor PHP Access Modifiers Readonly Properties PHP Inheritance Method Overriding The final Keyword PHP Class Constants PHP Abstract Classes PHP Interfaces Polymorphism PHP Traits PHP Static Methods PHP Static Properties Late Static Binding Magic Methods Object Cloning Comparing Objects Anonymous Classes PHP Enums PHP Namespaces Autoloading Classes PHP Iterables Iterators Object Serialization Strict Types Union Types Nullable Types Mixed and Never Types Nullsafe Operator PHP Attributes PHP Fibers Readonly Classes Property Hooks (PHP 8.4) Asymmetric Visibility (PHP 8.4) Reflection API SPL Data Structures MySQL Database MySQL Connect MySQL Create DB MySQL Create Table MySQL Insert Data MySQL Get Last ID MySQL Insert Multiple MySQL Prepared MySQL Select Data MySQL Where MySQL Order By MySQL Delete Data MySQL Update Data MySQL Limit Data MySQL Joins with PHP Pagination with PHP PDO Introduction PDO Connect PDO Prepared Statements PDO Fetch Modes PDO Transactions PDO Error Handling PHP XML Parsers PHP SimpleXML Parser PHP SimpleXML - Get PHP XML Expat Parser PHP DOM Parser PHP XMLReader PHP XMLWriter AJAX Intro AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll AJAX with JSON Security Introduction Password Hashing SQL Injection Prevention XSS Prevention CSRF Protection Session Security Secure Cookies File Upload Security Filesystem Security Error Reporting in Production Hiding PHP Encryption with Sodium PHP Configuration (php.ini) PHP Command Line (CLI) Composer PSR-4 Autoloading Installing Extensions (PECL / PIE) Debugging PHP OPcache & Performance Garbage Collection PHP-FPM Migrating to PHP 8 Project: Contact Form with Email Project: Login & Registration System Project: CRUD App with MySQL Project: Image Upload Gallery Project: Shopping Cart with Sessions Project: Simple Blog Project: REST API with PHP
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.