有沒有辦法使用對象屬性的值實例化一個新的類實例?$arg = 'hello';$class = $foo->bar;$instance = new $class($arg);這工作正常,但我想跳過第二行,只做類似的事情:$instance = new {$foo->bar}($arg);
1 回答

慕雪6442864
TA貢獻1812條經驗 獲得超5個贊
在 PHP 5.0.4+ 中,這可以正常工作:
$instance = new $foo->bar($arg);
完整示例:
<?php
$foo = new foo();
$arg = 'hello';
$class = $foo->bar;
$instance = new $class($arg);
$instance = new $foo->bar($arg); // your requested shorthand
class foo {
? ? public $bar = 'bar';
}
class bar {
? ? public function __construct($arg) {
? ? ? ? echo $arg;
? ? }
}
- 1 回答
- 0 關注
- 122 瀏覽
添加回答
舉報
0/150
提交
取消