4

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?

3 Answers 3

5

You can use reflection:

$f = new ReflectionFunction($callable);
$params = $f->getParameters();
echo $params[0]->getDefaultValue();
Sign up to request clarification or add additional context in comments.

2 Comments

Will ReflectionFunction work for any callable? (like class methods and static methods?)
@SparK No, it will not work. This was my case. You can take a look at my answer if you still need this.
3

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.

Comments

1

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.

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.