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

Asked

Viewed 511 times

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 something very good, because it brings dynamism to work with some methods or functions.

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

I tried to do so:

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

But that makes a mistake, because the __construct is not static.

PHP Warning: call_user_func_array() expects Parameter 1 to be a Valid callback, non-static method Arrayobject::__Construct() cannot be called statically

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

Just use the 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 won’t work.

Is there any way to instantiate a PHP class, using a array as a list of arguments, in the same way as call_user_func_array

1 answer

1


You can use Reflection to build 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 if you pass an empty array. If the class has no constructor it will play an Exception.

  • Congratulations, my son. You were quick on the trigger :D+1

  • 1

    If you want to simplify this bullshit there, you can do so (PHP 5.4 >=) $carro = (new ReflectionClass('Carro'))->newInstanceArgs(['Fiat', '2012'])

  • Um... I like the latest information from Exception. So it’s good to use the method getConstructor and check if it is null before :D

  • @Wallacemaxters, as in exact.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.