JackMahoney
JackMahoney

Reputation: 3433

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

})();

Upvotes: 7

Views: 500

Answers (2)

Nigel Alderton
Nigel Alderton

Reputation: 2376

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.

Upvotes: 1

Chris
Chris

Reputation: 58242

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.

Upvotes: 3

Related Questions