Last active
August 29, 2015 14:02
-
-
Save oh-sky/5ac0abe499e360a68f01 to your computer and use it in GitHub Desktop.
PHPで可変関数
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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