はじめに
PHPでは、その場限りでしか使わない「使い捨てオブジェクト」が欲しいケースがあります。
そんなときに活躍するのが 無名クラス(Anonymous Class) です。
本記事では、試験問題集でよく出題される 「無名クラス+コンストラクタプロパティプロモーション+__toString()」 の挙動について、図解を交えて整理してみます。
目次
無名クラスとは?
通常のクラス定義は以下のように名前をつけて行います。
class User {
// ...
}
しかし一度きりしか使わないなら、クラス名をつけるのは冗長です。
そこで登場するのが 無名クラス です。
$obj = new class {
// クラスの中身
};
- 名前を持たない
- 定義と同時にインスタンス化
- 「使い捨てオブジェクト」に便利
サンプルコード(試験問題例)
<?php
declare(strict_types=1);
error_reporting(-1);
$obj = new class(1, '2nd') {
public function __construct(
private int $num,
private string $str,
) {}
public function __toString(): string {
return "num is {$this->num}, str is {$this->str} \n";
}
};
echo $obj;
ASCIIアート図解
無名クラスの動作を図で表すと以下のようになります。
┌───────────────┐
│ new class(...)│ ← 名前を持たないクラスを生成
└───────┬───────┘
│
▼
┌───────────────┐
│ __construct │ ← (1, '2nd') を受け取り
│ num=1, str=2nd│ プロパティに代入
└───────┬───────┘
│
▼
┌───────────────┐
│ __toString │ ← echo $obj で呼ばれる
│ "num is 1, │
│ str is 2nd" │
└───────────────┘
コードのポイント
コンストラクタプロパティプロモーション
public function __construct(
private int $num,
private string $str,
) {}
private int $num
→ 自動で$this->num
を作成private string $str
→ 自動で$this->str
を作成new class(1, '2nd')
の呼び出しで、$num = 1
,$str = '2nd'
が代入される
__toString() の動作
public function __toString(): string {
return "num is {$this->num}, str is {$this->str} \n";
}
echo $obj;
で呼ばれる"num is 1, str is 2nd\n"
が返る
実行結果
num is 1, str is 2nd
✅ 問題文にある通り、この出力は 正しい です。(末尾の改行 \n
に注意!)
まとめ
- 無名クラスは
new class { ... };
で定義・即インスタンス化できる - コンストラクタプロパティプロモーション でプロパティ定義+代入を簡潔に書ける
- __toString() を実装すると
echo
でオブジェクトを文字列として出力可能