简体   繁体   中英

JavaScript “call on declare” anonymous functions equivalent in PHP?

I have some code that i want to be executed in a PHP script, but i don't want the variable created in this script to be visible otherwhere.

What i would like to do is like we can do using JavaScript :

(function() {
    // Do some stuff
})();

But i'd like to do this with PHP.

I've imagined the following code :

$main = function()
{
    global $main;
    unset($main);

    // Do some stuff
}

$main();

BUt it's not supported before PHP 5.3, and i need it to be.

Is there another way to do this with PHP 5.2 ?

Thanks in advance :)

You can use create_function() but this is ugly i think.

(I have a bigger problem with your code sample and maybe with your real code: you are using global state which is really bad.)

call_user_func(
    // create_function('$param1, $param2', '
    function($param1, $param2) { 
        // do stuff
    }
    // ')
, "param1", "param2");

Use the lines commented out for php < 5.3

But I think many people will agree this is a weird thing to do.

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