I encountered a weird problem with ReflectionFunction, described in ticket 44139 of PHP Bugs.
If for some reason you need to call with invoke, or invokeArgs, a function like array_unshift (that accepts internally the array by reference) you could use this code to avoid the generated warning or fatal error.
<?php
function unshift(){
$ref = new ReflectionFunction('array_unshift');
$arguments = func_get_args();
return $ref->invokeArgs(array_merge(array(&$this->arr), $arguments));
}
?>
I don't know about performances (you can create an array manually too, starting from array(&$this->something) and adding arguments). However, it seems to work correctly without problems, at least until the send by reference will be usable with one single value ...
ReflectionFunction::invokeArgs
(PHP 5 >= 5.1.0)
ReflectionFunction::invokeArgs — Invoca a la función con argumentos
Descripción
Invoca la función y pasa sus argumentos como array.
Parámetros
-
args -
Array con la lista de argumentos que se pasan a la función, similar a cómo funciona call_user_func_array().
Valores devueltos
Devuelve el resultado de la función invocada
Ejemplos
Ejemplo #1 Ejemplo de ReflectionFunction::invokeArgs()
<?php
function titulo($titulo, $nombre)
{
return sprintf("%s. %s\r\n", $titulo, $nombre);
}
$function = new ReflectionFunction('titulo');
echo $function->invokeArgs(array('Sr', 'Pedro'));
?>
El resultado del ejemplo sería:
Dr. Pedro
Ejemplo #2 Ejemplo de ReflectionFunction::invokeArgs() con argumentos por referencia
<?php
function obtener_condiciones_falsas(array $condiciones, array &$condiciones_falsas)
{
foreach ($condiciones as $condicion) {
if (!$condicion) {
$condiciones_falsas[] = $condicion;
}
}
}
$ref_a_funcion = new ReflectionFunction('obtener_condiciones_falsas');
$condiciones = array(true, false, -1, 0, 1);
$condiciones_falsas = array();
$ref_a_funcion->invokeArgs(array($condiciones, &$condiciones_falsas));
var_dump($condiciones_falsas);
?>
El resultado del ejemplo sería:
array(2) {
[0]=>
bool(false)
[1]=>
int(0)
}
Notas
Nota:
Si la función tiene argumentos que necesitan ser referencias, éstos deben ser referencias en la lista de argumentos pasados.
Ver también
- ReflectionFunction::invoke() - Invoca una función
- ReflectionFunctionAbstract::getNumberOfParameters() - Obtiene el número total de parámetros
- __invoke()
- call_user_func_array() - Llamar a una llamada de retorno un array de parámetros
Andrea Giammarchi ¶
5 years ago
