Search code examples
phpclassobjectinstantiation

Function to create objects by passing an array of parameters to __construct()?


I wonder if anyone know of a function to fully pragmatically create a class object similar to how call_user_func_array() works. What I want to do is pass a varying amount of parameters to the __construct().

I need something like:

$class = create_object('myobject', $array);

To have the behavior of;

$class = new myobject($array[0], $array[1], $array[2], ...);

Note: This is for a universal framework component so passing the whole array as the first construct parameter is not an option.


Solution

  • You can do this with PHP's features. You can unpack arrays as argument lists:

    function create_object($type, array $args = [])
    {
        return new $type(...$args);
    }
    

    Not sure the need for this though.