ID: 35747 Updated by: [EMAIL PROTECTED] Reported By: ckrack at i-z dot de -Status: Open +Status: Bogus Bug Type: Feature/Change Request Operating System: Any PHP Version: 5.1.1 New Comment:
You can use Reflection API for that. Previous Comments: ------------------------------------------------------------------------ [2005-12-20 17:34:11] ckrack at i-z dot de Description: ------------ I'd like to request a function to be able to create objects dynamically. I have a classname as string and an array containing parameters. The parameters can be imagined as fetched from func_get_args(). I now want to create an object out of these two, similar to how i would call a method or function using call_user_func_array(). There are three ways to implement this in PHP code, none of them are nice: - force classes to implement an 'init' function which receives the paramarray instead of the constructor. bad, because classes need to be changed. - use eval to create a statement like "new $classname($param1, $param2, $param3,....)". Eval however is bad and slow. - use a switch to check how many params are available, write a statement to create a class with each number of parameters. iirc there are about 180 params allowed (theoretically), so to cover all possibilitys, one would have to write about 180 cases ;) Reproduce code: --------------- function make_object($name, $params) { // make object instance if (is_array($params)) { // make object with multiple parameters switch(count($params)){ case 0: $obj = new $name(); break; case 1: $obj = new $name($params[0]); break; case 2: $obj = new $name($params[0], $params[1]); break; //etc,....... default: // DIRTY DIRTY but not possible in another way: we create the statement to call the class with multiple params $eval = "new ".$name."("; $eval .= implode(",", $params); $eval .= ")"; eval("\$obj = $eval;"); } // switch } else { // create object without parameters $obj = new $name(); } return $obj; } Expected result: ---------------- I want a function named something like "create_user_object_array" which receives a classname and a array containing parameters which are passed to the contructor of the class. Actual result: -------------- The provided code does what it should, but it is not in a nice style. lacking the possibilities. ------------------------------------------------------------------------ -- Edit this bug report at http://bugs.php.net/?id=35747&edit=1