是否无法使用对象属性的值实例化新的类实例?
$arg = 'hello';
$class = $foo->bar;
$instance = new $class($arg);
这很好用,但是我想跳过第二行,只是做些类似的事情:
$instance = new {$foo->bar}($arg);
答案 0 :(得分:1)
在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;
}
}
请参阅此working example。