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