1

Php version : 5.4

function foo(callable $succCallback) {

        $isCallable = is_callable($succCallback);
        echo "is callable outer ".is_callable($succCallback);
        $success = function($fileInfo) {
            echo "<br>is callable inner".is_callable($succCallback);
        };
        $this->calllll($success);
}
function calllll(callable $foo) {
  $foo("hello");
}

I define a function like that

And the output is

is callable outer 1
is callable inner

How can I refer to the $succCallback inside $success's body.

jilen
  • 5,633
  • 3
  • 35
  • 84

3 Answers3

6

You have to use use construct. It allows to inherit variables from the parent scope:

function foo(callable $succCallback) {

        $isCallable = is_callable($succCallback);
        echo "is callable outer ".is_callable($succCallback);
        $success = function($fileInfo) use($succCallback) {
            echo "<br>is callable inner".is_callable($succCallback);
        };
        $this->calllll($success);
}
hindmost
  • 7,125
  • 3
  • 27
  • 39
2
$success = function ($fileInfo) use ($succCallback) {
    echo "<br>is callable inner" . is_callable($succCallback);
};

To include variables from the surrounding scope inside anonymous functions, you need to explicitly extend their scope using use ().

deceze
  • 510,633
  • 85
  • 743
  • 889
2

To use variables from the parent scope, use use:

 $success = function($fileInfo) use ($succCallback) {
        echo "<br>is callable inner".is_callable($succCallback);
    };
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592