Skip to content

$this and Object Context

Inside an Instance Method, $this refers to the specific Object on which that Method is currently running.

final class Wallet
{
public function __construct(
public float $balance,
) {}
public function deposit(float $amount): void
{
$this->balance += $amount;
}
}
$first = new Wallet(100);
$second = new Wallet(500);
$first->deposit(20);
$second->deposit(50);

During the first call, $this refers to $first; during the second, it refers to $second. The Method has one definition, but it operates on the State of the receiving Object.

$this->property accesses an Instance Property. $this->method() calls another Instance Method on the same Object:

final class Wallet
{
public function __construct(
public float $balance,
) {}
public function deposit(float $amount): void
{
$this->ensurePositive($amount);
$this->balance += $amount;
}
private function ensurePositive(float $amount): void
{
if ($amount <= 0) {
throw new InvalidArgumentException();
}
}
}

Both accesses use the current Wallet Object.

A Static Method belongs to the Class-level context and is called without a receiving Object:

Wallet::showCurrent();

There is no current Object in that call, so $this is unavailable. Trying to use it from a Static Method fails with an error such as:

Using $this when not in object context

Static Members and their trade-offs are covered in depth in a later lesson.

final class Counter
{
public function __construct(
public int $value,
) {}
public function increment(): void
{
$this->value += 1;
}
public function incrementTwice(): void
{
$this->increment();
$this->increment();
}
}
$counter = new Counter(5);
$counter->incrementTwice();
echo $counter->value; // 7
  • Thinking $this represents every Object created from the Class.
  • Trying to use $this in Static Context.
  • Calling an Instance Member as if it were a Class-level Member.
  • Forgetting that the receiving Object determines which State changes.
  • Omitting void from Methods that intentionally return no value.
$this->property = access State on the current Object.
$this->method() = call Behavior on the current Object.
Static Context = no current Object, therefore no $this.
  1. What determines the Object referenced by $this?
  2. What does $this->increment() mean inside a Method?
  3. Why is $this unavailable in a Static Method?