Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Self Executing functions in PHP5.3?

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...

like image 987
AriehGlazer Avatar asked Oct 05 '10 16:10

AriehGlazer


People also ask

What are self executing functions?

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.

What are self-invoking functions explain with example?

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.

What is the syntax of self-invoking function?

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.

How do you call a function automatically in PHP?

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.


1 Answers

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 
like image 198
Gordon Avatar answered Sep 25 '22 02:09

Gordon