TarranJones
TarranJones

Reputation: 4242

How to get func_get_args & defaults to use with call_user_func_array

Is there a PHP function which can provide me with the arguments passed ( func_get_args) and any defaults which were not passed ?

Note: This function returns a copy of the passed arguments only, and does not account for default (non-passed) arguments.

Upvotes: 3

Views: 1601

Answers (2)

TarranJones
TarranJones

Reputation: 4242

Ive created a function called func_get_all_args which returns the same array as func_get_args but includes any missing default values.

function func_get_all_args($func, $func_get_args = array()){

    if((is_string($func) && function_exists($func)) || $func instanceof Closure){
        $ref = new ReflectionFunction($func);
    } else if(is_string($func) && !call_user_func_array('method_exists', explode('::', $func))){
        return $func_get_args;
    } else {
        $ref = new ReflectionMethod($func);
    }
    foreach ($ref->getParameters() as $key => $param) {

        if(!isset($func_get_args[ $key ]) && $param->isDefaultValueAvailable()){
            $func_get_args[ $key ] = $param->getDefaultValue();
        }
    }
    return $func_get_args;
}

Usage

function my_function(){

    $all_args = func_get_all_args(__FUNCTION__, func_get_args());
    call_user_func_array(__FUNCTION__, $all_args);
}

public function my_method(){

    $all_args = func_get_all_args(__METHOD__, func_get_args());
    // or
    $all_args = func_get_all_args(array($this, __FUNCTION__), func_get_args());

    call_user_func_array(array($this, __FUNCTION__), $all_args);
}

This could probably do with a bit of improvement such ac catching and throwing errors.

Upvotes: 0

Ruslan Osmanov
Ruslan Osmanov

Reputation: 21492

Use ReflectionFunction:

function test($a, $b = 10) {
  echo $a, ' ', $b;
}

$rf = new ReflectionFunction('test');
foreach ($rf->getParameters() as $p) {
  echo $p->getName(), ' - ', $p->isDefaultValueAvailable() ?
    $p->getDefaultValue() : 'none', PHP_EOL;
}

Upvotes: 2

Related Questions