投稿

ラベル(__invoke)が付いた投稿を表示しています

[PHP] マジックメソッド - クラスオブジェクトについての処理

クラスのオブジェクトに関するマジックメソッドについて3つほどまとめます。 __toStringメソッド __toStringメソッドは、クラスのオブジェクトを文字列として出力しようとした際に呼び出されるマジックメソッドです。 通常クラスのオブジェクトは、文字列として出力しようとしてもconvertエラーとなってしまい出力できません。 class Test { private string $name; public function __construct(string $name) { $this->name = $name; } } $test = new Test("Hoge"); echo "name=", $test, "\n"; $ php test_magic-method.php name= Fatal error: Uncaught Error: Object of class Test could not be converted to string in .¥test_magic-method.php:101 Stack trace: #0 {main} thrown in .\test_magic-method.php on line 101 これを解決するのが__toStringメソッドです。 マジックメソッドのシグネチャ 1. __toStringメソッドのシグネチャ アクセス修飾子 public メソッド名 __toString 戻り値 string [実装例]クラスオブジェクトの文字列変換 冒頭のコードに__toStringメソッドを実装して、文字列に変換した場合の出力を指定します。 コード class Test { private string $name; public function __construct(string $name) { $this->name = $name; } public functi