How can I instantiate a class using a 'function handling' style function?
I am trying to implement a Command Pattern style queue and I do not know how to pass arguments to the constructor of the object.
My 'Command' patte开发者_如何学JAVArn stores the objects in a database, where I have a table queue_items
storing my 'Command' objects, with the fields class
, method
, constructor_arguments
(stored as an indexed array), method_arguments
(stored as an indexed array), and object_type
(which is enum{'instance','static}
).
If object_type
is 'instance', I instantiate the object using the 'new' keyword. If object_type
is 'static', then I just make the call using forward_static_call_array()
.
If I have no constructor arguments, I can just use something like this:
$instance = new $class_name(); //NOTE: no arguments in the constructor
$result = call_user_func_array(array($instance, $method_name), $method_arguments);
But if I wish to pass the values from the constructor_arguments
into the __construct()
, I can not find a function to let me do this.
I wish to keep the indexed array and not to rely on specialised constructors, so that I do not have to rewrite my own and 3rd party classes I use to handle, for example, taking an associative array as the only argument in a constructor.
Does anyone know how to pass an indexed array directly into __construct
in the fashion of call_user_func_array()
? Or can it simply not be done?
Drew J. Sonne.
You can use the ReflectionClass
for this special case:
$rc = new ReflectionClass($className);
$instance = $rc->newInstanceArgs($array_of_parameters);
A more elaborated example using ReflectionClass:
<?php
class MyClass
{
private $arg1;
private $arg2;
public function __construct($arg1, $arg2 = "Hello World")
{
$this->arg1 = $arg1;
$this->arg2 = $arg2;
}
public function print(){
echo $this->arg2 . "," .$this->arg2;
}
}
$class = new ReflectionClass('MyClass');
$args = array(3,"outro");
$instance = $class->newInstanceArgs($args);
$instance->print()
?>
精彩评论