简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM