PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
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.
<?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
Two quesions:
Which is best?
Does anyone have better?
Last edited by Ollie Saunders on Fri Aug 11, 2006 2:26 pm, edited 1 time in total.
$reflection = new ReflectionClass($name);
$constructor = $reflection->getConstructor();
// requires a 1nd arg of object instance, which obviously doesn't exist
// yet because its a constructor
return $constructor->invokeArgs(null, $params);
$reflection = new ReflectionClass($name);
// Passes a single parameter, $params array to __construct().
// not several parameters
return $reflection->newInstance($params);
// This is what I want, if it existed
return $reflection->newInstanceArray($params);