Andrew
Andrew

Reputation: 3462

Is it possible to reference an anonymous function from within itself in PHP?

I'm trying to do something like the following:

// assume $f is an arg to the wrapping function
$self = $this;
$func = function() use($f, $ctx, $self){

    $self->remove($func, $ctx); // I want $func to be a reference to this anon function

    $args = func_get_args();
    call_user_func_array($f, $args);
};

Is it possible to reference the function assigned to $func from with the same function?

Upvotes: 18

Views: 2888

Answers (3)

Jon
Jon

Reputation: 437574

Yes, it is possible if you use a variable by reference. For example:

$func = function($i) use(&$func) {
    if ($i <= 0) {
        return;
    }
    echo "Countdown: $i.\n";
    $func($i - 1);
};

$func(3);

Upvotes: 4

Naftali
Naftali

Reputation: 146310

Yes you can

See this example: http://php.net/manual/en/functions.anonymous.php#105564


Code from example:

<?php
    $fib = function($n) use(&$fib) {
        if($n == 0 || $n == 1) return 1;
        return $fib($n - 1) + $fib($n - 2);
    };

   echo $fib(2) . "\n"; // 2
   $lie = $fib;
   $fib = function(){die('error');};//rewrite $fib variable 
   echo $lie(5); // error   because $fib is referenced by closure

?>

Upvotes: 4

Alex Turpin
Alex Turpin

Reputation: 47776

Try doing

$func = function() use (/*your variables,*/ &$func) {
    var_dump($func);
    return 1;
};

http://codepad.viper-7.com/cLd3Fu

Upvotes: 26

Related Questions