Calling constructor \w variable length arg-list dynamically
Posted: Fri Aug 11, 2006 8:46 am
OK I want to instantiate a class with a parameterized constructed via the method of another class. Normally you just use call_user_func_array() and be done with it but that doesn't seem to work for constructors.
Two quesions:
Code: Select all
<?php
class ComplexClass_A
{
public $result;
public function __construct($a, $b, $c)
{
$this->result = $a + $b + $c;
}
public static function init($a, $b, $c)
{
$instance = new self;
$instance->result = $a + $b + $c;
return $instance;
}
}
class ComplexFactory
{
public function factory()
{
$params = func_get_args();
$name = 'ComplexClass_' . $params[0];
unset($params[0]);
/* Warning: call_user_func_array(): First argument is expected to be a
valid callback, 'ComplexClass_A' was given */
return call_user_func_array($name, $params);
/* Strict Standards: Non-static method ComplexClass_A::__construct()
cannot be called statically */
// In addition to being an E_STRICT this also returns NULL
return call_user_func_array(array($name, '__construct'), $params);
// This works but its pretty manky and would take ages to implement completely
$sQuot = '\'';
foreach ($params as $k => $v) {
if (is_string($v)) {
$params[$k] = $sQuot . addcslashes($v, $sQuot) . $sQuot;
} else if (is_array($v)) {
// need recursion now to generate array() structure, ughewk i say.
}
}
return eval('return new '. $name . '(' . implode(',', $params) . ');');
// Finally, don't use the constructor at all not so great but also works
return call_user_func_array(array($name, 'init'), $params);
}
}
$factory = new ComplexFactory();
$a = $factory->factory('A', 1, 2, 3);
echo $a->result; // Desired: 6- Which is best?
- Does anyone have better?