ReflectionClass:newInstance()(或newInstanceArgs())讓你這樣做。
例如
class Foo {
public function __construct() {
$p = func_get_args();
echo 'Foo::__construct(', join(',', $p), ') invoked';
}
}
$rc = new ReflectionClass('Foo');
$foo = $rc->newInstanceArgs(array(1,2,3,4,5));
編輯:無ReflectionClass大概PHP4兼容(不好意思,手頭沒有PHP4現在)
class Foo {
public function __construct() {
$p = func_get_args();
echo 'Foo::__construct(', join(',', $p), ') invoked';
}
}
$class = 'Foo';
$rc = new $class(1,2,3,4);
速度對比: 由於反射的速度已經在這裏提到的是一個小(合成)測試
define('ITERATIONS', 100000);
class Foo {
protected $something;
public function __construct() {
$p = func_get_args();
$this->something = 'Foo::__construct('.join(',', $p).')';
}
}
$rcStatic=new ReflectionClass('Foo');
$fns = array(
'direct new'=>function() { $obj = new Foo(1,2,3,4); },
'indirect new'=>function() { $class='Foo'; $obj = new $class(1,2,3,4); },
'reflection'=>function() { $rc=new ReflectionClass('Foo'); $obj = $rc->newInstanceArgs(array(1,2,3,4)); },
'reflection cached'=>function() use ($rcStatic) { $obj = $rcStatic->newInstanceArgs(array(1,2,3,4)); },
);
sleep(1);
foreach($fns as $name=>$f) {
$start = microtime(true);
for($i=0; $i<ITERATIONS; $i++) {
$f();
}
$end = microtime(true);
echo $name, ': ', $end-$start, "\n";
sleep(1);
}
它打印在我的(沒那麼快)筆記本
direct new: 0.71329689025879
indirect new: 0.75944685935974
reflection: 1.3510940074921
reflection cached: 1.0181720256805
不是那麼糟,是嗎?
爲什麼你想這樣做呢?你想解決什麼問題? – Skilldrick 2009-12-18 16:11:09
@Skilldrick:在我的情況下,試圖實現一個簡單的依賴注入容器。 – 2010-03-28 20:58:19
[如何在PHP中使用call調用構造函數\ _user \ _func \ _array]的可能重複(http://stackoverflow.com/questions/2409237/how-to-call-the-constructor-with-call-user- func-array-in-php) – Maks3w 2015-11-13 20:16:06