Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 338
Andrew Avatar asked Oct 24 '11 15:10

Andrew


People also ask

Does PHP have anonymous functions?

Besides named functions, PHP allows you to define anonymous functions. An anonymous function is a function that doesn't have a name. Since the function doesn't have a name, you need to end it with a semicolon ( ; ) because PHP treats it as an expression.

Which statement is not allowed in anonymous function?

As of PHP 7.1, these variables must not include superglobals, $this , or variables with the same name as a parameter. A return type declaration of the function has to be placed after the use clause.

What is anonymous function explain with example in PHP?

Anonymous function is a function without any user defined name. Such a function is also called closure or lambda function. Sometimes, you may want a function for one time use. Closure is an anonymous function which closes over the environment in which it is defined. You need to specify use keyword in it.

How can you pass a local variable to an anonymous function in PHP?

Yes, use a closure: functionName($someArgument, function() use(&$variable) { $variable = "something"; }); Note that in order for you to be able to modify $variable and retrieve the modified value outside of the scope of the anonymous function, it must be referenced in the closure using & . It's new!


1 Answers

Try doing

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

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

like image 85
Alex Turpin Avatar answered Sep 28 '22 14:09

Alex Turpin