上級 › __toString未実装のオブジェクトを文字列化した原因 › パターン4
__toString未実装のオブジェクトを文字列化した原因
__toString()メソッドを持たないオブジェクトを文字列と連結したり、文字列として出力しようとしたりすると致命的エラーになります。
1 <?php 2 class Weight { 3 public function __construct(public int $grams) {} 4 } 5 $w = new Weight(300); 6 echo "Weight: " . __________________; ^
Fatal error: Uncaught Error: Object of class Weight could not be converted to string in main.php:6
空欄を埋めて実行を通す
Weightクラスは__toString()を持たないため、オブジェクトそのものを文字列と連結できません。
次の問題