0

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.

tim
  • 2,530
  • 3
  • 26
  • 45

2 Answers2

0

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.

lagbox
  • 48,571
  • 8
  • 72
  • 83
  • Thanks for replying. I see the three dots is actually a thing in PHP 5.6 called splat operator. I presume there is no other option for PHP 5.4+ which is the minimum requirement for this platform. – tim Dec 18 '20 at 19:51
  • 1
    Yes the three dots ... https://www.php.net/manual/en/migration56.new-features.php#migration56.new-features.splat – AbraCadaver Dec 18 '20 at 19:53
0

For PHP <5.6 this can be achieved using ReflectionClass.

function create_object($class_name, $args=array()) {
  $reflect = new ReflectionClass($class_name);
  return $reflect->newInstanceArgs($args);
}

Note: ReflectionClass is twice as slow as the splat operator. https://stackoverflow.com/a/24648651/1135440

tim
  • 2,530
  • 3
  • 26
  • 45