How to instantiate a class in php using an array as an argument (same as call_user_func_array)?

0

In php, when I can invoke a function, using a array as if I were passing each argument in sequence.

Example:

  function soma_a_b($a, $b)
  {
        return $a + $b;
  }

If I had an array with two elements, I could do it in two ways. So:

    $array = [4, 6];

    soma_a_b($array[0], $array[1]);

Or so:

  call_user_func_array('soma_a_b', $array);

This also works for class methods. For example:

class Soma
{
      public function resultado($a, $b)
      {
          return $a + $b;
      }
}


$soma = new Soma;

call_user_func_array([$soma, 'resultado'], $array);

When the class method is static, we can do it in two ways:

  call_user_func_array('Soma::resultado', $array);

  call_user_func_array(['Soma', 'resultado'], $array);

This is a very good thing, because it brings dynamism to working with some methods or functions.

But I need this functionality when creating an instance of the class. That is, in the constructor.

I tried to do this:

 call_user_func_array(['ArrayObject', '__construct'], [1, 2]);

But this gives error, because __construct is not static.

  

PHP warning: call_user_func_array () expects parameter 1 to be a valid callback, non-static method ArrayObject :: __ construct () can not be called statically

I know there is a way to do this in versions equal to or greater than PHP 5.6 .

Just use variadic args :

 class Carro
 {
       public function __construct($tipo, $ano)
       {}
 }

 $args = ['Tipo', '2015'];

 $soma = new Soma(...$args);

However, I still use PHP 5.4. So the above example will not work.

Is there any way to instantiate a class in PHP, using array as argument list, just as it does with call_user_func_array

    
asked by anonymous 19.04.2016 / 15:28

1 answer

1

You can use Reflection to construct an instance of a class by passing the parameters as an array.

<?php
  $class = new ReflectionClass('Carro');
  $instance = $class->newInstanceArgs(array('fiat', '2012'));
?>

The newInstanceArgs method will call the constructor even though you pass an empty array. If the class has no constructor it will throw an Exception.

    
19.04.2016 / 15:32