Last Updated: February 25, 2016
·
965
· eclipxe13

PHP self invoking work-around

Did you ever envy the JS syntax for:

(function(){
    // some code…
})();

You can do it on PHP, this is an example:

call_user_func(function() {
    // some code ...
});

It is not exactly a self invoking, is most like call an anonymous function, but does the same thing.

You can even include some external variables by use or parameters.

Reasons to use it:

  • You don't want to declare a function that will only be called once
  • You don't want that the variables in that function goes to global namespace

Please comment another scenarios you might use it, i.e. I'm using this in a bootstrap file.