tags:

views:

183

answers:

2

Hi all,

I would like to dynamically create a PHP object, and parameters would be optional.

For example, instead of doing this:

$test = new Obj($param);

I would like to do something like this (create new ob is fictional):

$test = create_new_obj('Obj', $param);

Is there such function in php? Something similar to call_user_func_array, but for object instead.

+3  A: 

You can dynamically create an object as long as you know the class name:

$objName = 'myClass';
$test = new $objName($param);

You could easily define a __construct() function to take default arguments as well if that was a requirement of your construction logic.

[Edit note]: This is a concept known as variable variables, and there's some examples in the manual where the new command is introduced.

zombat
+2  A: 

Since some constructors may take a different number of arguments, this way can accommodate easily.

$r = new ReflectionClass($strClassName);
$foo = $r->newInstanceArgs($arrayOfConstructorArgs);
chris
Reflection is expensive. You'd be better off using `func_get_args()` for this.
zombat
In my tests using reflection in php isn't slower than func\_get\_args(). Plus you don't have to change the code of the classes.
VolkerK