Understanding $this-> in PHP: Object-Oriented Programming Basics

Understanding $this-> in PHP: Object-Oriented Programming Basics

In PHP classes, $this refers to the current object instance. The -> operator accesses properties and methods on that instance:

class User {
    private string $name;
    
    public function __construct(string $name) {
        $this->name = $name;
    }
    
    public function getName(): string {
        return $this->name;
    }
}

$user = new User("Alice");
echo $user->getName();  // "Alice"

Inside the getName() method, $this->name accesses the $name property of the specific User object that called the method. Each instance has its own properties. $this lets you access them.

Why $this Exists

Without $this, methods couldn't distinguish between instance properties and local variables:

class Counter {
    private int $count = 0;
    
    public function increment(): void {
        $count++;  // This is a local variable, not the property!
    }
}

This doesn't work. $count++ creates a local variable, not touching the instance property. You need $this:

public function increment(): void {
    $this->count++;  // Accesses the instance property
}

Accessing Properties

Properties are accessed with $this->propertyName. Note: no dollar sign on the property name after the arrow:

$this->name     // Correct
$this->$name    // Wrong (unless $name is a variable variable)

Visibility modifiers (private, protected, public) don't affect $this access. Inside a class, $this can access private properties:

class BankAccount {
    private float $balance;
    
    public function deposit(float $amount): void {
        $this->balance += $amount;  // Fine - same class
    }
}

Calling Methods

Methods are called the same way:

class Calculator {
    public function add(int $a, int $b): int {
        return $a + $b;
    }
    
    public function addAndDouble(int $a, int $b): int {
        return $this->add($a, $b) * 2;
    }
}

$this->add() calls the add() method on the current object. This works even if the method is private:

private function validate(): bool {
    return $this->isValid();  // Can call private methods
}

$this vs self vs static

PHP has three ways to reference class-related things: $this, self, and static. They're not interchangeable.

$this references the current object instance:

$this->property    // Instance property
$this->method()    // Instance method

self references the class where the code is written:

self::CONSTANT        // Class constant
self::staticMethod()  // Static method

static uses late static binding (the class that was called):

static::staticMethod()  // Resolves at runtime

Example showing the difference:

class Parent {
    public static function who(): string {
        return "Parent";
    }
    
    public static function testSelf(): string {
        return self::who();  // Always "Parent"
    }
    
    public static function testStatic(): string {
        return static::who();  // Depends on caller
    }
}

class Child extends Parent {
    public static function who(): string {
        return "Child";
    }
}

echo Child::testSelf();    // "Parent"
echo Child::testStatic();  // "Child"

self resolves to Parent because that's where the code is written. static resolves to Child because that's what was called. For instance methods and properties, always use $this.

Method Chaining

Returning $this enables method chaining:

class StringBuilder {
    private string $value = "";
    
    public function append(string $text): self {
        $this->value .= $text;
        return $this;
    }
    
    public function upper(): self {
        $this->value = strtoupper($this->value);
        return $this;
    }
    
    public function get(): string {
        return $this->value;
    }
}

$result = (new StringBuilder())
    ->append("hello")
    ->append(" world")
    ->upper()
    ->get();

echo $result;  // "HELLO WORLD"

Each method modifies the object and returns $this, allowing the next method call.

Constructor Usage

Constructors use $this to initialize properties:

class Product {
    private string $name;
    private float $price;
    
    public function __construct(string $name, float $price) {
        $this->name = $name;
        $this->price = $price;
    }
}

PHP 8.0 introduced constructor property promotion, which reduces boilerplate:

class Product {
    public function __construct(
        private string $name,
        private float $price
    ) {
        // Properties are declared and assigned automatically
    }
}

Behind the scenes, this still uses $this->name and $this->price, but you don't write it explicitly.

When $this Isn't Available

Static methods don't have $this because they're not called on an instance:

class Math {
    public static function add(int $a, int $b): int {
        return $a + $b;
    }
}

Math::add(2, 3);  // No object instance

Trying to use $this in a static method is an error:

public static function example(): void {
    echo $this->property;  // Fatal error
}

Common Mistakes

Forgetting the dollar sign on $this:

this->name = "Alice";  // Parse error - missing $

Using $this in static context:

public static function test(): void {
    $this->method();  // Error - no instance
}

Double dollar sign on property names:

$this->$property  // Variable variable (probably not intended)
$this->property   // Direct property access

Accessing Other Object Instances

You can access private properties of other instances of the same class:

class Point {
    private float $x;
    private float $y;
    
    public function __construct(float $x, float $y) {
        $this->x = $x;
        $this->y = $y;
    }
    
    public function distanceTo(Point $other): float {
        $dx = $this->x - $other->x;  // Can access $other's private property
        $dy = $this->y - $other->y;
        return sqrt($dx * $dx + $dy * $dy);
    }
}

This works because both objects are instances of Point. Privacy is per-class, not per-instance.

Arrow Functions and $this

In PHP 7.4+, arrow functions inherit $this from the surrounding scope:

class Numbers {
    private array $values = [1, 2, 3];
    
    public function double(): array {
        return array_map(
            fn($n) => $n * $this->multiplier,  // $this available
            $this->values
        );
    }
}

Regular anonymous functions don't inherit $this unless you bind it explicitly:

$callback = function() {
    return $this->property;  // Error unless bound
};

Null Object Pattern

Sometimes $this patterns lead to fluent interfaces that handle nulls:

class OptionalValue {
    private mixed $value;
    
    public function map(callable $fn): self {
        if ($this->value !== null) {
            $this->value = $fn($this->value);
        }
        return $this;
    }
}

$result = (new OptionalValue(5))
    ->map(fn($x) => $x * 2)
    ->map(fn($x) => $x + 1);

Further Reading

The PHP manual's section on object-oriented basics covers $this, properties, and methods.

For late static binding and the difference between self and static, see the late static binding documentation.

Constructor property promotion is explained in the PHP 8.0 release notes.

$this-> is foundational to object-oriented PHP. 

Wear the code

Product mockup

$this-> Developer T-Shirt (PHP Edition — Dark Mode)

£25.00

View product
Product mockup

$this-> Developer T-Shirt (PHP Edition — Light Mode)

£25.00

View product

0 comments

Leave a comment

Please note, comments need to be approved before they are published.