Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Get all parameters from a function (even the optional one)

Tags:

php

I want to get all parameters (passed or not) from a function.

Example:

<?php
    function foo($a, $b=1)
    {
         return $a-$b;
    }
?>

If I call

$test = func_get_args(foo(10));
var_dump($test);

I will have only an array with [0] => 10.

How can I have the value(s) of the optional parameter(s) even if I don’t pass it/them? (I know that func_get_args only returns passed parameters.)

EDIT: To be more precise, here is what I’m doing:

function insertLog($fct_name="-1", $type="-1", $error="-1", ....)
{
     // first thing
     $params = func_get_args();
     var_dump($params);
}
like image 733
Stv Avatar asked Feb 13 '14 17:02

Stv


2 Answers

You can accomplish this using the ReflectionFunction function class.

function foo($a, $b=1)
{
    $arr = array();
    $ref = new ReflectionFunction(__FUNCTION__);
    foreach($ref->getParameters() as $parameter)
    {
        $name = $parameter->getName();
        $arr[$name] = ${$name};
    }
    print_r($arr);

    // ...
}

Calling the function:

foo(1);

Output:

Array
(
    [a] => 1
    [b] => 1
)

Demo

like image 77
Amal Murali Avatar answered Oct 04 '22 21:10

Amal Murali


func_get_args

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

Ive created a function called func_get_all_args which takes advantage of Reflection. It 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.

like image 25
TarranJones Avatar answered Oct 04 '22 23:10

TarranJones