I'm a JS developer and use self-executing anonymous functions routinely to minimize pollution of the global scope.
ie: (JS)
(function(){
var x = ...
})();
Is the same technique possible / advisable in PHP to minimize function / variable name clashes?
ie: (PHP)
(function(){
$x = 2;
function loop($a){
...
}
loop($x);
})();
To avoid global pollution, use classes and an object oriented approach: See PHP docs here
To further avoid pollution, avoid static and global variables.
Closures like the one you have shown is used in Javascript is due to the fact that it (Javascript) is a prototype based language, with out properties (in the formative sense) normally shown in a OO based language.
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 isn't as pretty as the Javascript equivalent, but it does the same job. I find that construct very useful and use it often.
You may also return values like this;
$str = call_user_func(function() {
$a = 'foo';
return $a;
});
echo($str); // foo
echo($a); // Causes 'Undefined variable' error.
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