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
@ स्किलड्रिक: मेरे मामले में, एक साधारण निर्भरता इंजेक्शन कंटेनर को लागू करने की कोशिश कर रहा है। –
संभावित डुप्लिकेट [PHP में कॉल \ _user \ _func \ _array के साथ कन्स्ट्रक्टर को कैसे कॉल करें] (http://stackoverflow.com/questions/2409237/how-to-call-the-constructor-with-call-user- func-array-in-php) – Maks3w