__call magic creating new classes in PHP
I am using the __call magic within some of my mvc code to produce an autoloadable forms framework but I have ran into a problem I am hoping some one on here might have a work around for.
The __call magic takes two paramters: $methodName and $arguments. The arguments come back as an array of args which you called. Normally this function is called on methods you can do as such so feed these arguments into a function:
call_user_func_array($methodName, $arguments);
And this w开发者_开发知识库ill propogate the methods signature with the arguments. I am trying to do something a little more complex. I am attempting to propogate a classes constructor the same way, through being able to send maybe a imploded comma deliminenated array of the arguments into the classes constructor or just sending the args in directly but both of these do not produce the required result. When I send an imploded array down into the constructor PHP thinks it's a string and when I send the array it thinks it's an array.
This is the code I am using atm:
public function __call($method, $args){
return $this->init_element(new $method($args['name'], $args['value'], $args['opts']));
}
What if I had 4 arguments to pass down though? Is there a way I can get it to dynamically fill the constructor just like you can for a function using call_user_func_array()?
I could use an attributes() function to do this but I would really like to be able to do it like I can with functions.
Thanks in advance,
Use PHP's reflection classes: (http://php.net/manual/en/class.reflectionclass.php)
$obj = new ReflectionClass( $classname );
then
$ins = $obj->newInstanceArgs( $arguments );
or
$ins = $obj->newInstance( );
I saw the following somewhere around the web:
call_user_func_array(array($obj, '__construct'), $args);
精彩评论