Skip to content

Instantly share code, notes, and snippets.

@oh-sky
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oh-sky/5ac0abe499e360a68f01 to your computer and use it in GitHub Desktop.
Save oh-sky/5ac0abe499e360a68f01 to your computer and use it in GitHub Desktop.
PHPで可変関数
<?php
function add($number1, $number2) {
return $number1 + $number2;
}
$func = 'add';
echo $func(1, 1);
// -> 2
echo 'add'(1, 1);
// -> Error
echo call_user_func($func, 1, 2);
// -> 3
echo call_user_func('add', 2, 3);
// -> 5
echo call_user_func_array($func, array(3, 5));
// -> 8
echo call_user_func_array(
function ($n1, $n2) {return $n1 + $n2;},
array(5, 8)
);
// -> 13
<?php
$json = <<<JSON
[
{
"name":"max",
"arguments":[1, 2, 3]
},
{
"name":"sqrt",
"arguments":[16]
}
]
JSON;
$methods = json_decode($json);
foreach ($methods as $method) {
var_dump(call_user_func_array($method->name, $method->arguments));
}
// -> int(3)
// -> double(4)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment