Skip to content

Instantly share code, notes, and snippets.

@koohq
Last active October 16, 2018 16:36
Show Gist options
  • Save koohq/765f2d99c1979643ef648198866bcde4 to your computer and use it in GitHub Desktop.
Save koohq/765f2d99c1979643ef648198866bcde4 to your computer and use it in GitHub Desktop.
A function that calls the function with exact parameters' count.
<?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);
}
<?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