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,422
  • 1
  • 31
  • 82

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,026
  • 3
  • 25
  • 37
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
  • 491,798
  • 79
  • 706
  • 853
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
  • 311,322
  • 76
  • 447
  • 566