Skip to content

PHP Tutorial Object-Oriented PHP

The $this Keyword

Lesson 206 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

Inside a method, $this means “the object this method was called on”.

index.php
PHP
<?php
class Greeter
{
    public function __construct(private string $name) {}

    public function hello(): string
    {
        return "Hello, " . $this->name;
    }
}

$a = new Greeter("Ana");
$b = new Greeter("Ben");

echo $a->hello() . "\n";
echo $b->hello();
Output
OUTPUT
Hello, Ana
Hello, Ben

The same method code runs for both objects. $this->name is Ana’s name in the first call and Ben’s in the second.

Reading and writing properties

index.php
PHP
<?php
class Counter
{
    private int $count = 0;

    public function add(int $n): void
    {
        $this->count += $n;
    }

    public function get(): int
    {
        return $this->count;
    }
}

$c = new Counter();
$c->add(5);
$c->add(3);

echo $c->get();
Output
OUTPUT
8

Without $this, you get a local variable

Forgetting $this-> is the most common beginner mistake.

index.php
PHP
<?php
class Counter
{
    private int $count = 0;

    public function add(int $n): void
    {
        $count = $this->count + $n;   // creates a LOCAL variable, not the property
    }

    public function get(): int
    {
        return $this->count;
    }
}

$c = new Counter();
$c->add(5);

echo $c->get();
Output
OUTPUT
0

The property never changed, because the method wrote to a local $count. Use $this->count = ....

Calling other methods

index.php
PHP
<?php
class Rectangle
{
    public function __construct(private float $w, private float $h) {}

    private function area(): float
    {
        return $this->w * $this->h;
    }

    public function describe(): string
    {
        return "Area: " . $this->area();
    }
}

echo (new Rectangle(3, 4))->describe();
Output
OUTPUT
Area: 12

Returning $this for chaining

index.php
PHP
<?php
class Html
{
    private string $out = "";

    public function open(string $tag): static
    {
        $this->out .= "<$tag>";
        return $this;
    }

    public function text(string $text): static
    {
        $this->out .= htmlspecialchars($text);
        return $this;
    }

    public function close(string $tag): static
    {
        $this->out .= "</$tag>";
        return $this;
    }

    public function __toString(): string
    {
        return $this->out;
    }
}

echo (new Html())->open("p")->text("Tom & Jerry")->close("p");
Output
OUTPUT
<p>Tom &amp; Jerry</p>

$this is not available in static methods

A static method belongs to the class, not to an object, so there is no $this. Using it gives an error.

$this inside closures

A closure created inside a method automatically keeps $this. A static function does not. See Closures.

warning
Forgetting $this->
If a property never changes and you see no error, look for a method that assigns to a plain variable of the same name. Always write $this->name.