phpのクラスの要素をアロー演算子を使って呼び出すとき、他のクラスの要素や関数の戻り値を使用したいときどのように記述すればよいのでしょうか。
<?php class hoge{ public $x; function __construct($a){ $this->x = $a; } } class hogehoge{ public $y; function __construct($a){ $this->y = $a; } } $sample = new hoge('y'); $sample_2 = new hogehoge('zzz'); //このように記述したいです。 echo $sample_2->($sample->x); ?>気になる質問をクリップする
クリップした質問は、後からいつでもMYページで確認できます。
またクリップした質問に回答があった際、通知やメールを受け取ることができます。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
回答2件
0
ベストアンサー
まず、PHPのコンストラクタはconstruct
ではなく__construct
です。
http://php.net/manual/ja/language.oop5.decon.php
で、ご質問の回答としては、可変変数を{}
で囲うことで実現できます。
http://php.net/manual/ja/language.variables.variable.php
php
1<?php 2 class hoge{ 3 public $x; 4 function __construct($a){ 5 $this->x = $a; 6 } 7 } 8 class hogehoge{ 9 public $y; 10 function __construct($a){ 11 $this->y = $a; 12 } 13 } 14 $sample = new hoge('y'); 15 $sample_2 = new hogehoge('zzz'); 16 17 echo $sample_2->{$sample->x}; 18?>
実行結果
zzz
関数で可変変数を使用するとしたら、以下のような感じでしょうか。
php
1<?php 2 class hoge{ 3 public $x; 4 function __construct($a){ 5 $this->x = $a; 6 } 7 8 function x() { 9 return $this->x; 10 } 11 } 12 class hogehoge{ 13 public $y; 14 function __construct($a){ 15 $this->y = $a; 16 } 17 18 function y() { 19 return $this->y; 20 } 21 } 22 $sample = new hoge('y'); 23 $sample_2 = new hogehoge('zzz'); 24 25 echo $sample_2->{$sample->x()}(); 26?>
実行結果
zzz
もっとも、これで可読性が向上するかというとはなはだ疑問ですが。。
投稿2016/03/26 07:01
総合スコア4791
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2016/03/26 07:12
退会済みユーザー
2016/03/26 07:14
2016/03/26 07:17
退会済みユーザー
2016/03/26 07:17
2016/03/26 07:30
0
仮にこのように記述したとして
PHP
1$sample = new hoge('y'); 2$sample_2 = new hogehoge('zzz'); 3 4echo $sample_2->($sample->x);
echoで出力したい値は一体何ですか?
他のクラスの要素を使用したいなら
$sample = new hoge('y'); $sample_2 = new hogehoge($sample->x);
こういうことがしたいのでしょうか?
他のクラスの関数の戻り値を使用したいなら
class hoge{ public $x; function __construct($a){ $this->x = $a; return $this->x; } } class hogehoge{ public $y; function __construct($a){ $this->y = $a; return $this->y; } } echo new hogehage(new hoge('y'));
こういうことがしたいのでしょうか?
投稿2016/03/26 06:23
編集2016/03/26 06:33退会済みユーザー
総合スコア0
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2016/03/26 06:31
退会済みユーザー
2016/03/26 06:41
退会済みユーザー
2016/03/26 07:00
退会済みユーザー
2016/03/26 07:05
退会済みユーザー
2016/03/26 07:06
2016/03/26 07:08
退会済みユーザー
2016/03/26 07:11
あなたの回答
tips
太字
斜体
打ち消し線
見出し
引用テキストの挿入
コードの挿入
リンクの挿入
リストの挿入
番号リストの挿入
表の挿入
水平線の挿入
プレビュー
質問の解決につながる回答をしましょう。 サンプルコードなど、より具体的な説明があると質問者の理解の助けになります。 また、読む側のことを考えた、分かりやすい文章を心がけましょう。