Last Updated: February 25, 2016
·
1.138K
· 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.

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Related Tags
#php
Did you know?

PHP applications still send a browser full of JavaScript. Hardening the server does not inventory the payment, analytics, and plugin scripts that run after the HTML is delivered.

Security insights from Cside