$this and Object Context
Inside an Instance Method, $this refers to the specific Object on which that
Method is currently running.
The current Object
Section titled “The current Object”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.
Accessing Instance Members
Section titled “Accessing Instance Members”$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.
Static Context
Section titled “Static Context”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 contextStatic Members and their trade-offs are covered in depth in a later lesson.
Practical example
Section titled “Practical example”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; // 7Common mistakes
Section titled “Common mistakes”- Thinking
$thisrepresents every Object created from the Class. - Trying to use
$thisin Static Context. - Calling an Instance Member as if it were a Class-level Member.
- Forgetting that the receiving Object determines which State changes.
- Omitting
voidfrom Methods that intentionally return no value.
Summary
Section titled “Summary”$this->property = access State on the current Object.$this->method() = call Behavior on the current Object.Static Context = no current Object, therefore no $this.Knowledge check
Section titled “Knowledge check”- What determines the Object referenced by
$this? - What does
$this->increment()mean inside a Method? - Why is
$thisunavailable in a Static Method?