PHP 8.3.4 Released!

ReflectionFunction::invokeArgs

(PHP 5 >= 5.1.2, PHP 7, PHP 8)

ReflectionFunction::invokeArgsInvoca a la función con argumentos

Descripción

public ReflectionFunction::invokeArgs(array $args): mixed

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

add a note

User Contributed Notes 2 notes

up
0
theyourcomputer at gmail dot com
6 years ago
In the case of call_user_func_array(), if you were to pass around an anonymous function and reference $this within the anonymous function, $this will faithfully refer to the class in the context in which the function was defined. Using ReflectionFunction::invokeArgs() does not seem to retain its original context--yeah, even if you bind the anonymous function before invoking. I recommend call_user_func_array() where context is a concern.
up
0
Andrea Giammarchi
16 years ago
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 ...
To Top