Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call the current anonymous function in PHP?

Tags:

php

I have an anonymous function which is supposed to call itself. However, I have no variable or function name at hand, so I was hoping to find a function that could do return "this" in context of functions. Is there such a thing?

Here's an example:

$f = function() use($bar, $foo) {   // call this function again. }; 

Calling like this:

call_user_func(__FUNCTION__); 

Leads to this:

Warning: call_user_func() expects parameter 1 to be a valid callback, function '{closure}' not found or invalid function name

If I try to put $f in the use-list, then it says the variable is not defined (because it is not yet).

like image 508
Tower Avatar asked Nov 29 '11 12:11

Tower


People also ask

How do you call an anonymous function?

The () makes the anonymous function an expression that returns a function object. An anonymous function is not accessible after its initial creation. Therefore, you often need to assign it to a variable. In this example, the anonymous function has no name between the function keyword and parentheses () .

Does PHP have anonymous functions?

Anonymous functions ¶ Anonymous functions, also known as closures , allow the creation of functions which have no specified name. They are most useful as the value of callable parameters, but they have many other uses. Anonymous functions are implemented using the Closure class.

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 do you call a function automatically in PHP?

' . PHP_EOL . PHP_EOL;; } else { $method = array_shift($args); // first argument is the method name and we won't need to pass it further if (method_exists($this, $method)) { echo __FUNCTION__ . ': I will execute this line and then call ' .


1 Answers

__FUNCTION__ cannot be used in anonymous functions

Pass the variable holding the anonymous function as a reference in the 'use' clause....

$f = function() use($bar, $foo, &$f) {    $f(); }; 

Tip of the hat to this answer.

like image 64
2 revs Avatar answered Sep 29 '22 20:09

2 revs