Re: dynamic object instances

From: Date: Thu, 11 Aug 2005 00:46:02 +0000
Subject: Re: dynamic object instances
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-220391@lists.php.net to get a copy of this message
Thomas Angst wrote:
Hello List, I would like to create an object inside a function with its classname and a parameter list submitted by the function call. function create($class, $parameter) { $obj = new $class($parameter); return $obj; } This is working very well. But I have not every time the same count of parameters for a class constructor. If this is a normal method call of an object I can realise it like this: $ret = call_user_func_array(array(&$obj, 'method'), $parameter_array); The $parameter_array contains as many entries as the function needs. Works well too. But how can I write a function to instance objects with various count of parameters in the constructor? I know, can do this with an eval. But I would like to find a solution where I don't need an eval.
to keep it easy have your ctors be able to except an assoc array as the first argument as an alternative to its normal arg list - or just use an assoc array period - that combined with a call to expand() in the ctor. then... something like: function create($class, $params) { if (!class_exists($class)) { return null; } return new $class( $params ); } <TAKE_NOTE> btw if your on php4 your probably what to be using lots of f'ing '&' signs. </TAKE_NOTE> alternatively it's either: 1. use eval() - yuck 2. make all your objects have empty ctors and force them to have an _init() method that actually does the work e.g. function create($class) { if (!class_exists($class)) { return null; } $params = func_get_args(); $params = array_slice($params, 1); $o = new $class(); call_user_func_array(array($o, '_init'), $params); return $o; } 3. re-evaluate what you are trying to achieve with the create function. maybe you need a factory base class instead? (for instance)
thanks for all answers, Thomas


« previous php.general (#220391) next »