Helen Che
Helen Che

Reputation: 2011

Get PHP callable arguments as an array?

Say I have a callable stored as a variable:

$callable = function($foo = 'bar', $baz = ...) { return...; }

How would I get 'bar'?

if (is_callable($callable)) {
  return func_get_args();
}

Unfortunately func_get_args() is for the current function, is it possible to get a key value pair of arguments?

Upvotes: 4

Views: 3237

Answers (3)

miile7
miile7

Reputation: 2393

I came across this question because I was looking for getting the arguments for a callable which is not just the function itself. My case is

class MyClass{
    public function f(){
        // do some stuff
    }
}

$myclass = new MyClass();
$callable = array($myclass, "f);

This is a valid callback in php. In this case the solution given by @Marek does not work.

I worked around with phps is_callable function. You can get the name of the function by using the third parameter. Then you have to check whether your callback is a function or a (class/object) method. Otherwise the Reflection-classes will mess up.

if($callable instanceof Closure){
    $name = "";
    is_callable($callable, false, $name);

    if(strpos($name, "::") !== false){
        $r = new ReflectionMethod($name);
    }
    else{
        $r = new ReflectionFunction($name);
    }
}
else{
    $r = new ReflectionFunction($callable);
}

$parameters = $r->getParameters();
// ...

This also returns the correct value for ReflectionFunctionAbstract::isStatic() even though the $name always uses :: which normally indicates a static function (with some exceptions).


Note: In PHP>=7.0 this may be easier using Closures. There you can do someting like

$closure = Closure::fromCallable($callable);

$r = new ReflectionFunction($closure);

You may also cause have to distinguish between ReflectionFunction and ReflectionMethod but I can't test this because I am not using PHP>=7.0.

Upvotes: 3

Marek
Marek

Reputation: 7433

You can use reflection:

$f = new ReflectionFunction($callable);
$params = $f->getParameters();
echo $params[0]->getDefaultValue();

Upvotes: 5

Ma'moon Al-Akash
Ma'moon Al-Akash

Reputation: 5403

You may want to use get_defined_vars to accomplish this, this function will return an array of all defined variables, specifically by accessing the callable index from the output array.

Upvotes: 1

Related Questions