3

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.

2

2 Answers 2

2

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

is there a differance between isDefaultValueAvailable() and isOptional(), surely the only way to make a paramanter optional is to provide a default value?
isOptional vs isDefaultValueAvailable stackoverflow.com/questions/23774355/…
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.