Reputation: 10447
This may be a bit of an XY questions, so I'm going to explain what I'm trying to do first. I'm attempting to create a single php file to handle all of my page refresh AJAX calls. That means I want to be able to send it a class name, plus a list of the variables that the class constructor takes, and for it to then create the class.
I can create the class fine. $class = new $className();
works just fine for creating the class. The problem is passing in the default variables. Most of the variables are objects containing other classes, so I can't just include this once the class is created, I need to pass them as the class is created.
I was thinking something along the lines of:
$varStr = '';
$s = '';
foreach($vars as $var) {
switch($var['type']) {
case 'object':
$varStr .= $s . '$' . $var['value'];
break;
case 'variable':
$varStr .= $s . $var['value'];
}
$s = ',';
}
$class = new $className(echo $varStr);
Now obviously echo $varStr isn't going to work there, but I have no idea what will. Is there anything I can do that will output the variables from my array into the class constructor like that? Is what I'm trying to do even possible? Is there a better way?
Whilst I understand I could just pass the whole array to the class constructor, this would complicate the main part of the program, and I would rather just ditch the idea of a single page for AJAX refresh than go down that route.
Upvotes: 1
Views: 281
Reputation: 21249
This is a wild guess at what you're trying to do but maybe this is what you're after:
// Generate constructor args
$args = array();
foreach($vars as $var) {
switch($var['type']) {
$value = $var['value'];
case 'object':
args[] = ${$value}; // evaluate, I think that's what you want?
break;
case 'variable':
args[] = $value; // use as is
break;
}
}
// Instanciate class with args
$class = new ReflectionClass($className);
$obj = $class->newInstanceArgs($args);
For this to work, it would require $vars to enumerates args in the correct order expected by each class constructor.
Upvotes: 1
Reputation: 522081
So basically you're trying to pass a variable number of arguments to a constructor? In a regular function, you could do something like:
function foo() {
$args = func_get_args();
...
}
call_user_func_array('foo', array('bar', 'baz'));
This won't work for constructors, since the calling mechanism is different. You could do:
class Foo {
public function __construct() {
$args = func_get_args();
...
}
}
$class = new ReflectionClass('Foo');
$obj = $class->newInstanceArgs(array('bar', 'baz'));
But really, what you should be doing is this:
class Foo {
public function __construct(array $args) {
...
}
}
$obj = new Foo(array('bar', 'baz'));
or
class Foo {
public function __construct($bar, $baz) {
...
}
}
$obj = new Foo('bar', 'baz');
Anything else is quite insane. If your object constructor is so complicated, you probably need to simplify it.
Upvotes: 7