Transferring variables in anonymous functions in PHP

I am a JS developer and regularly perform autonomous anonymous functions to minimize global pollution.

ie: (JS)

(function(){ var x = ... })(); 

Is the same technique possible / appropriate in PHP to minimize function / variable name conflicts?

ie: (PHP)

 (function(){ $x = 2; function loop($a){ ... } loop($x); })(); 
+7
source share
2 answers

To avoid global pollution, use classes and an object-oriented approach: See PHP docs here

To avoid contamination, avoid static and global variables.

Closures like the ones you showed are used in Javascript because it (Javascript) is a prototype-based language with properties (in a formative sense) usually shown in OO.

+3
source

Yes, you can create anonymous functions in PHP that execute immediately without polluting the global namespace;

 call_user_func(function() { $a = 'hi'; echo $a; }); 

The syntax is not as pretty as the Javascript equivalent, but it does the same job. I think the design is very useful and often uses it.

You can also return the following values:

 $str = call_user_func(function() { $a = 'foo'; return $a; }); echo($str); // foo echo($a); // Causes 'Undefined variable' error. 
+1
source

All Articles