PHPの $this は、クラスのメソッド内から現在のインスタンス自身を指す擬似変数です。メソッドの中で同じオブジェクトのプロパティやメソッドにアクセスするために使います。
$this はPHPが自動的に設定する特殊な変数で、開発者が明示的に定義する必要はありません。オブジェクト指向プログラミングにおいて、クラス内のデータと処理を結びつける重要な役割を担います。
基本的な使い方
$this->プロパティ名 でプロパティに、$this->メソッド名() でメソッドにアクセスします。
PHP
<?php
class User {
public string $name;
public int $age;
public function __construct(string $name, int $age) {
// $thisで自身のプロパティに値を設定
$this->name = $name;
$this->age = $age;
}
public function greet(): string {
// $thisで自身のプロパティにアクセス
return "私は{$this->name}、{$this->age}歳です。";
}
public function introduce(): string {
// $thisで自身のメソッドを呼び出す
return $this->greet() . " よろしくお願いします!";
}
}
$user = new User("田中", 30);
echo $user->introduce() . "\n";
実行結果
私は田中、30歳です。 よろしくお願いします!
$this は常に「そのメソッドを呼び出しているインスタンス」を指します。同じクラスから複数のインスタンスを作っても、それぞれの $this は自分自身のデータにアクセスします。
インスタンスごとの$this
PHP
<?php
class Counter {
private int $count = 0;
private string $label;
public function __construct(string $label) {
$this->label = $label;
}
public function increment(): void {
$this->count++;
}
public function show(): void {
echo "{$this->label}: {$this->count}\n";
}
}
$a = new Counter("カウンターA");
$b = new Counter("カウンターB");
$a->increment();
$a->increment();
$a->increment();
$b->increment();
$a->show();
$b->show();
実行結果
カウンターA: 3
カウンターB: 1
$a の $this は $a 自身、$b の $this は $b 自身を指すため、それぞれ独立してカウントされます。
メソッドチェーンでの$this活用
メソッドの戻り値として $this を返すと、メソッドチェーン(fluent interface)が実現できます。
PHP
<?php
class HtmlBuilder {
private string $html = "";
public function addHeading(string $text, int $level = 1): self {
$this->html .= "<h{$level}>{$text}</h{$level}>\n";
return $this; // $thisを返す
}
public function addParagraph(string $text): self {
$this->html .= "<p>{$text}</p>\n";
return $this;
}
public function addList(array $items): self {
$this->html .= "<ul>\n";
foreach ($items as $item) {
$this->html .= " <li>{$item}</li>\n";
}
$this->html .= "</ul>\n";
return $this;
}
public function build(): string {
return $this->html;
}
}
$html = (new HtmlBuilder())
->addHeading("PHPチュートリアル")
->addParagraph("PHPのクラスについて学びましょう。")
->addList(["プロパティ", "メソッド", "\$this"])
->build();
echo $html;
実行結果
<h1>PHPチュートリアル</h1>
<p>PHPのクラスについて学びましょう。</p>
<ul>
<li>プロパティ</li>
<li>メソッド</li>
<li>$this</li>
</ul>
実用的な例
PHP
<?php
class BankAccount {
private float $balance;
private array $history = [];
public function __construct(private string $owner, float $initialBalance = 0) {
$this->balance = $initialBalance;
$this->log("口座開設(初期残高: {$initialBalance}円)");
}
public function deposit(float $amount): void {
$this->balance += $amount;
$this->log("入金: {$amount}円");
}
public function withdraw(float $amount): bool {
if ($amount > $this->balance) {
$this->log("出金失敗: {$amount}円(残高不足)");
return false;
}
$this->balance -= $amount;
$this->log("出金: {$amount}円");
return true;
}
private function log(string $message): void {
$this->history[] = date("H:i:s") . " " . $message;
}
public function showHistory(): void {
echo "=== {$this->owner}の取引履歴 ===\n";
foreach ($this->history as $entry) {
echo " {$entry}\n";
}
echo " 残高: {$this->balance}円\n";
}
}
$account = new BankAccount("田中太郎", 10000);
$account->deposit(5000);
$account->withdraw(3000);
$account->withdraw(20000);
$account->showHistory();
実行結果
=== 田中太郎の取引履歴 ===
10:00:00 口座開設(初期残高: 10000円)
10:00:00 入金: 5000円
10:00:00 出金: 3000円
10:00:00 出金失敗: 20000円(残高不足)
残高: 12000円
$thisとselfの違い
$this はインスタンスを指し、インスタンスのプロパティやメソッドにアクセスします。一方、self はクラス自身を指し、静的プロパティ、静的メソッド、クラス定数にアクセスするときに使います。$this は静的メソッド内では使えません。
注意
静的メソッド(static キーワード付きのメソッド)の中では $this は使用できません。静的メソッドはインスタンスなしで呼び出されるため、参照すべきインスタンスが存在しないためです。
まとめ
$thisはメソッド内から現在のインスタンス自身を参照する擬似変数$this->プロパティ名や$this->メソッド名()で自身にアクセスする- 各インスタンスの
$thisはそれぞれ独立した自分自身を指す return $thisでメソッドチェーンが実現できる- 静的メソッド内では
$thisは使用できない