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?
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.
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.
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.
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!
Try doing
$func = function() use (/*your variables,*/ &$func) {
var_dump($func);
return 1;
};
http://codepad.viper-7.com/cLd3Fu
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With