You are here: Re: dynamic object instances « PHP « IT news, forums, messages
Re: dynamic object instances

Posted by Matthew Weier O'Phinney on 08/10/05 21:53

* Thomas Angst <ta_php@granitsoft.ch>:
> 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.

Use the func_* functions, along with array_shift(). In addition, you'll
need to use either a standard-named static instantiator, or the class
name as the constructor method:

function create($class) {
$args = func_get_args();
array_shift($args); // remove $class from the args list

// Do this if using a standard-named static instantiator method
// across classes; in this case 'init':
return call_user_func_array(array($class, 'init'), $args);

// Or use a function named after the class name as the instantiator
// method (ala PHP4):
return call_user_func_array(array($class, $class), $args);
}


--
Matthew Weier O'Phinney
Zend Certified Engineer
http://weierophinney.net/matthew/

 

Navigation:

[Reply to this message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация