是否有一个call_user_func()等效于创建一个新的类实例? [英] Is there a call_user_func() equivalent to create a new class instance?
问题描述
如何创建一个具有给定数组的参数的类发送给构造函数?
How can I create a class with a given array of arguments to be sent to the constructor? Something along the lines of:
class a {
var $args = false;
function a() {$this->args = func_get_args();}
}
$a = call_user_func_array('new a',array(1,2,3));
print_r($a->args);
理想情况下,这需要在PHP4和PHP5中工作,无需修改类。任何想法?
Ideally this needs to work, without modification to the class, in both PHP4 and PHP5. Any ideas?
推荐答案
ReflectionClass:newInstance()(或newInstanceArgs())让你这样做。
ReflectionClass:newInstance() (or newInstanceArgs()) let's you do that.
例如
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)
edit: without ReflectionClass and probably php4 compatible (sorry, no php4 at hand right now)
class Foo {
public function __construct() {
$p = func_get_args();
echo 'Foo::__construct(', join(',', $p), ') invoked';
}
}
$class = 'Foo';
$rc = new $class(1,2,3,4);
速度比较:
由于反射的速度已经在这里提到了一点test
speed comparison: Since the speed of reflection has been mentioned here's a little (synthetic) test
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);
}
$ b
which prints on my (not so fast) notebook
direct new: 0.71329689025879
indirect new: 0.75944685935974
reflection: 1.3510940074921
reflection cached: 1.0181720256805
这不是很糟糕吗?
这篇关于是否有一个call_user_func()等效于创建一个新的类实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!