実現したいこと
該当のソースコードについて、
26,27行目の// インスタンス作成
では$this
が参照できるのに対して、
28,29行目の// アクション実行
ではできない理由を知りたいです。
エラーメッセージ
PHP Fatal error: Uncaught Error: Object of class ParentClass could not be converted to string in /workspace/Main.php:29
該当のソースコード
php
1<?php 2class ChildClass 3{ 4 public function hoge(): string 5 { 6 return 'hoge!!'; 7 } 8} 9 10class ParentClass 11{ 12 13 private string $className; 14 private string $actionName; 15 16 public function __construct( 17 string $className, 18 string $actionName, 19 ) { 20 $this->className = $className; 21 $this->actionName = $actionName; 22 } 23 24 public function toto(): string 25 { 26 // インスタンス作成 27 $instance = new $this->className(); 28 // アクション実行 29 return $instance->$this->actionName(); 30 } 31 32} 33 34$instance = new ParentClass('ChildClass', 'hoge'); 35echo $instance->toto();
試したこと
次のtiti
やtata
のような形でエラーの解消はできました。
php
1class ParentClass 2{ 3 4 // 省略 5 6 public function titi(): string 7 { 8 // インスタンス作成 9 $instance = new $this->className(); 10 // アクション実行 11 return $instance->{$this->actionName}(); 12 } 13 14 public function tata(): string 15 { 16 // インスタンス作成 17 $instance = new $this->className(); 18 // アクション実行 19 $actionName = $this->actionName; 20 return $instance->$actionName(); 21 } 22} 23 24$instance = new ParentClass('ChildClass', 'hoge'); 25echo $instance->titi(); 26echo $instance->tata();
ですがtoto
において「なぜインタンス作成で同じようなエラーにならないのか」がよく理解できない状態です。
そこが知りたいので、インスタンス作成とアクション実行における$this
の取り扱いの違いという質問になりますでしょうか。
ご回答よろしくお願い致します。
補足情報(FW/ツールのバージョンなど)
PHP 8.1.9 です。

回答1件
あなたの回答
tips
プレビュー
下記のような回答は推奨されていません。
このような回答には修正を依頼しましょう。
また依頼した内容が修正された場合は、修正依頼を取り消すようにしましょう。
2023/05/15 15:07