Last active
October 16, 2018 16:36
-
-
Save koohq/765f2d99c1979643ef648198866bcde4 to your computer and use it in GitHub Desktop.
A function that calls the function with exact parameters' count.
This file contains 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 | |
/** | |
* CallFuncExact.php | |
* | |
* @copyright 2018 koohq | |
* @license https://creativecommons.org/publicdomain/zero/1.0/legalcode CC0 | |
*/ | |
/** | |
* @param callable $func | |
* @param mixed $args,... | |
* @return mixed | |
*/ | |
function callFuncExact(callable $func, ...$args) | |
{ | |
if (is_array($func)) { | |
$rf = new ReflectionMethod(...$func); | |
} elseif ($func instanceof Closure || function_exists($func)) { | |
$rf = new ReflectionFunction($func); | |
} else { | |
$rf = new ReflectionMethod($func); | |
} | |
$params = $rf->getParameters(); | |
$numOfParams = count($params); | |
if ($numOfParams === 0) { | |
return call_user_func($func); | |
} | |
if ($params[$numOfParams - 1]->isVariadic()) { | |
return call_user_func_array($func, $args); | |
} | |
$slicedArgs = array_slice($args, 0, $numOfParams); | |
return call_user_func_array($func, $slicedArgs); | |
} |
This file contains 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 | |
# A. PHP Warning | |
is_string(1, 2, 3); | |
# B. Without PHP Warning | |
callFuncExact('is_string', 1, 2, 3); | |
# is_string(1); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment