phpday 2027 - Call for Papers

ReflectionFunction::invokeArgs

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

ReflectionFunction::invokeArgs — 引数を指定して関数を起動する

説明

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

関数を起動して、その引数を配列として渡します。

パラメータ

args

関数に渡す引数を含む配列。 call_user_func_array() と同じように動作します。

args のキーがすべて数値の場合、キーは無視され、 各要素は位置を指定した引数として順に関数に渡されます。

args のキーに文字列のものがある場合、 その要素は、キーを名前とする名前付き引数として関数に渡されます。

args 内で数値のキーが文字列のキーより後に現れた場合、 または文字列のキーが関数のどのパラメータの名前とも一致しない場合、 Error がスローされます。

戻り値

起動した関数の結果を返します。

変更履歴

バージョン 説明
8.0.0 args のキーは、 静かに無視されるのではなく、パラメータの名前として解釈されるようになりました。

例

例1 ReflectionFunction::invokeArgs() の例

<?php
function title($title, $name)
{
    return sprintf("%s. %s\r\n", $title, $name);
}

$function = new ReflectionFunction('title');

echo $function->invokeArgs(array('Dr', 'Phil'));
?>

上の例の出力は以下となります。

Dr. Phil

例2 ReflectionFunction::invokeArgs() で参照を使う例

<?php
function get_false_conditions(array $conditions, array &$false_conditions)
{
    foreach ($conditions as $condition) {
        if (!$condition) {
            $false_conditions[] = $condition;
        }
    }
}

$function_ref     = new ReflectionFunction('get_false_conditions');

$conditions       = array(true, false, -1, 0, 1);
$false_conditions = array();

$function_ref->invokeArgs(array($conditions, &$false_conditions));

var_dump($false_conditions);
?>

上の例の出力は以下となります。

array(2) {
  [0]=>
  bool(false)
  [1]=>
  int(0)
}

注意

注意:

関数の引数の中にリファレンス渡しを要するものがある場合は、 渡す引数の中でもリファレンスにしておく必要があります。

参考

User Contributed Notes 2 notes

up
0
theyourcomputer at gmail dot com
8 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
18 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 ...
Adding new notes is disabled. Please see the links in the Found A Problem? section.
To Top