Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrapping variables in anonymous functions in PHP

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);

})();
like image 407
JackMahoney Avatar asked Feb 13 '13 04:02

JackMahoney


2 Answers

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.

like image 62
Chris Avatar answered Oct 24 '22 02:10

Chris


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.
like image 1
Nigel Alderton Avatar answered Oct 24 '22 02:10

Nigel Alderton