CakeFest 2024: The Official CakePHP Conference

call_user_func_array

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

call_user_func_arrayパラメータの配列を指定してコールバック関数をコールする

説明

call_user_func_array(callable $callback, array $args): mixed

args にパラメータを指定して、 callback で指定したユーザー定義関数をコールします。

パラメータ

callback

コールするcallable

args

コールバック関数に渡すパラメータを指定する配列。

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

args のキーのいずれかが文字列の場合、 それらの要素は callback の名前付き引数として渡されます。 その場合、名前は配列のキーが使われます。

args の数値のキーが文字列のキーの後に現れたり、 文字列のキーが callback の パラメータの名前にマッチしない場合、致命的なエラーが発生します。

戻り値

コールバック関数の結果、あるいはエラー時に false を返します。

変更履歴

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

例1 call_user_func_array() の例

<?php
function foobar($arg, $arg2) {
echo
__FUNCTION__, " got $arg and $arg2\n";
}
class
foo {
function
bar($arg, $arg2) {
echo
__METHOD__, " got $arg and $arg2\n";
}
}


// foobar() 関数に引数を 2 つ渡してコールします
call_user_func_array("foobar", array("one", "two"));

// $foo->bar() メソッドに引数を 2 つ渡してコールします
$foo = new foo;
call_user_func_array(array($foo, "bar"), array("three", "four"));
?>

上の例の出力は、 たとえば以下のようになります。

foobar got one and two
foo::bar got three and four

例2 call_user_func_array() での名前空間の使用法

<?php

namespace Foobar;

class
Foo {
static public function
test($name) {
print
"Hello {$name}!\n";
}
}

call_user_func_array(__NAMESPACE__ .'\Foo::test', array('Hannes'));

call_user_func_array(array(__NAMESPACE__ .'\Foo', 'test'), array('Philip'));

?>

上の例の出力は、 たとえば以下のようになります。

Hello Hannes!
Hello Philip!

例3 ラムダ関数の使用

<?php

$func
= function($arg1, $arg2) {
return
$arg1 * $arg2;
};

var_dump(call_user_func_array($func, array(2, 4)));

?>

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

int(8)

例4 値の参照渡し

<?php

function mega(&$a){
$a = 55;
echo
"function mega \$a=$a\n";
}
$bar = 77;
call_user_func_array('mega',array(&$bar));
echo
"global \$bar=$bar\n";

?>

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

function mega $a=55
global $bar=55

例5 call_user_func_array() を名前付き引数と一緒に使う

<?php
function foobar($first, $second) {
echo
__FUNCTION__, " got $first and $second\n";
}

// foobar() を名前付き引数を使いつつ、位置を指定せずにコールする
call_user_func_array("foobar", array("second" => "two", "first" => "one"));

// foobar() を名前付き引数をひとつだけ使ってコールする
call_user_func_array("foobar", array("foo", "second" => "bar"));

// Fatal error: Cannot use positional argument after named argument
call_user_func_array("foobar", array("first" => "one", "bar"));

?>

上の例の出力は、 たとえば以下のようになります。

foobar got one and two
foobar got foo and bar

Fatal error: Uncaught Error: Cannot use positional argument after named argument

注意

注意:

call_user_func()call_user_func_array() で登録されたコールバックは、 前のコールバックからスローされた例外がキャッチされていない場合はコールされません。

参考

add a note

User Contributed Notes 4 notes

up
55
admin at torntech dot com
8 years ago
As of PHP 5.6 you can utilize argument unpacking as an alternative to call_user_func_array, and is often 3 to 4 times faster.

<?php
function foo ($a, $b) {
return
$a + $b;
}

$func = 'foo';
$values = array(1, 2);
call_user_func_array($func, $values);
//returns 3

$func(...$values);
//returns 3
?>

Benchmarks from https://gist.github.com/nikic/6390366
cufa with 0 args took 0.43453288078308
switch with 0 args took 0.24134302139282
unpack with 0 args took 0.12418699264526
cufa with 5 args took 0.73408579826355
switch with 5 args took 0.49595499038696
unpack with 5 args took 0.18640494346619
cufa with 100 args took 5.0327250957489
switch with 100 args took 5.291127204895
unpack with 100 args took 1.2362589836121
up
37
sebastian dot rapetti at tim dot it
3 years ago
Using PHP 8, call_user_func_array call callback function using named arguments if an array with keys is passed to $args parameter, if the array used has only values, arguments are passed positionally.

<?php

function test(string $param1, string $param2): void
{
echo
$param1.' '.$param2;
}

$args = ['hello', 'world'];
//hello world
call_user_func_array('test', $args);

$args = ['param2' => 'world', 'param1' => 'hello'];
//hello world
call_user_func_array('test', $args);

$args = ['unknown_param' => 'hello', 'param2' => 'world'];
//Fatal error: Uncaught Error: Unknown named parameter $unknown_param
call_user_func_array('test', $args);
?>
up
1
alangiderick at gmail dot com
6 months ago
It's quite interesting reading the notes in this page especially the one that mentions the difference between argument unpacking being significantly faster than calling `call_user_func_array()` directly by admin at torntech dot com.

This is true for PHP 5 but as from PHP 7.0+, there is no significant difference in the run-time between these two mechanisms of operation. The time taken is almost, if not the same for both operations, so this is already something that tells me that the PHP run-time environment has changed quite a lot (for the PHP 7 rewrite).

I used the example from admin at torntech dot com to check this hypothesis.
up
-2
james at gogo dot co dot nz
19 years ago
Be aware the call_user_func_array always returns by value, as demonstrated here...

<?php
function &foo(&$a)
{
return
$a;
}

$b = 2;
$c =& call_user_func_array('foo', array(&$b));
$c++;
echo
$b . ' ' . $c;
?>

outputs "2 3", rather than the expected "3 3".

Here is a function you can use in place of call_user_func_array which returns a reference to the result of the function call.

<?php
function &ref_call_user_func_array($callable, $args)
{
if(
is_scalar($callable))
{
// $callable is the name of a function
$call = $callable;
}
else
{
if(
is_object($callable[0]))
{
// $callable is an object and a method name
$call = "\$callable[0]->{$callable[1]}";
}
else
{
// $callable is a class name and a static method
$call = "{$callable[0]}::{$callable[1]}";
}
}

// Note because the keys in $args might be strings
// we do this in a slightly round about way.
$argumentString = array();
$argumentKeys = array_keys($args);
foreach(
$argumentKeys as $argK)
{
$argumentString[] = "\$args[$argumentKeys[$argK]]";
}
$argumentString = implode($argumentString, ', ');
// Note also that eval doesn't return references, so we
// work around it in this way...
eval("\$result =& {$call}({$argumentString});");
return
$result;
}
?>
To Top