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
Congratulations, my son. You were quick on the trigger :D+1
– Wallace Maxters
If you want to simplify this bullshit there, you can do so (PHP 5.4 >=)
$carro = (new ReflectionClass('Carro'))->newInstanceArgs(['Fiat', '2012'])
– Wallace Maxters
Um... I like the latest information from
Exception
. So it’s good to use the methodgetConstructor
and check if it is null before :D– Wallace Maxters
@Wallacemaxters, as in exact.
– Vinicius Zaramella