Inside a method, $this means “the object this method was called on”.
<?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();
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
<?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();
8
Without $this, you get a local variable
Forgetting $this-> is the most common beginner mistake.
<?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();
0
The property never changed, because the method wrote to a local $count. Use $this->count = ....
Calling other methods
<?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();
Area: 12
Returning $this for chaining
<?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");
<p>Tom & 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.
Forgetting $this->
$this->name.