marcelobm Posted September 15, 2011 Share Posted September 15, 2011 Hi there every one, i'm writing a class that create instances of other classes and I want to use the __call() magic method to make it more compact and dynamic. here is a basic example of what I'm trying to achieve. The code bellow is the working code. <?php class creator{ private $objects = array(); public function createObj1($param1, $param2, $param3){ $this->objects[]=new Obj1($param1, $param2, $param3); } public function createObj2($param1, $param2){ $this->objects[]=new Obj2($param1, $param2); } } ?> Now I want the same functionality but using just the __call(), something like this <?php class creator{ private $objects = array(); public function __call($name, $args){ $this->objects[]=new $name($param1, $param2); } } ?> So, the main problem is, in the $args variable i get an array with all the args passed, How can I make the call to create a new object when in the object constructor are individual parameters needed and not an array of parameters. Thank you in advance. Link to comment https://forums.phpfreaks.com/topic/247202-using-the-__call-magic-method/ Share on other sites More sharing options...
marcelobm Posted September 15, 2011 Author Share Posted September 15, 2011 I solved it this way: <?php <?php class creator{ private $objects = array(); public function __call($name, $args){ $func = ''; for($i=0; $i < count($args); $i++){ $func .= "\$arguments[{$i}], "; } $func = "new ".$name."(".substr($func, 0, -2).");"; eval("\$this->objects[] = $func"); } } ?> This work perfect, but if any of you have a better Idea i'll be glad to hear it Link to comment https://forums.phpfreaks.com/topic/247202-using-the-__call-magic-method/#findComment-1269609 Share on other sites More sharing options...
AbraCadaver Posted September 15, 2011 Share Posted September 15, 2011 http://us.php.net/manual/en/function.call-user-func-array.php Link to comment https://forums.phpfreaks.com/topic/247202-using-the-__call-magic-method/#findComment-1269635 Share on other sites More sharing options...
ManiacDan Posted September 15, 2011 Share Posted September 15, 2011 Don't ever use eval() for something like this, a solution like call_user_func_array is the most correct solution. Eval() is for testing, debugging, and for when you've reached a level of skill where you know for a fact that PHP cannot do what you need it to do with the native functionality. -Dan Link to comment https://forums.phpfreaks.com/topic/247202-using-the-__call-magic-method/#findComment-1269644 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.