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

})();

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.
链接地址: http://www.djcxy.com/p/69322.html

上一篇: 在VS 2012中的代码中

下一篇: 在PHP中封装匿名函数中的变量