I was trying to borrow some programing paradigms from JS to PHP (just for fun). Is there a way of doing:
$a = (function(){ return 'a'; })();
I was thinking that with the combination of use
this can be a nice way to hide variables JS style
$a = (function(){ $hidden = 'a'; return function($new) use (&$hidden){ $hidden = $new; return $hidden; }; })();
right now I need to do:
$temp = function(){....}; $a = $temp();
It seems pointless...
The self-executing anonymous function is a special function which is invoked right after it is defined. There is no need to call this function anywhere in the script. This type of function has no name and hence it is called an anonymous function. The function has a trailing set of parenthesis.
A self-invoking (also called self-executing) function is a nameless (anonymous) function that is invoked immediately after its definition. An anonymous function is enclosed inside a set of parentheses followed by another set of parentheses () , which does the execution. (function(){ console. log(Math.
Self-Invoking Functions A self-invoking expression is invoked (started) automatically, without being called. Function expressions will execute automatically if the expression is followed by (). You cannot self-invoke a function declaration.
The only way to do this is using the magic __call . You need to make all methods private so they are not accessable from the outside. Then define the __call method to handle the method calls.
Function Call Chaining, e.g. foo()()
is in discussion for PHP5.4. Until then, use call_user_func
:
$a = call_user_func(function(){ $hidden = 'a'; return function($new) use (&$hidden){ $hidden = $new; return $hidden; }; }); $a('foo'); var_dump($a);
gives:
object(Closure)#2 (2) { ["static"]=> array(1) { ["hidden"]=> string(3) "foo" } ["parameter"]=> array(1) { ["$new"]=> string(10) "<required>" } }
As of PHP7, you can immediately execute anonymous functions like this:
(function() { echo 123; })(); // will print 123
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