Alex Rivera | Logout

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

Asked 2011-10-24T15:23:46.500
18

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?

Edit
Report

1 Answer

3

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

?>
answered 2011-10-24T15:28:49.927

Your Answer