How do I immediately execute an anonymous function in PHP?

前端 未结 9 978
离开以前
离开以前 2020-11-27 03:29

In JavaScript, you can define anonymous functions that are executed immediately:

(function () { /* do something */ })()

Can you do somethin

相关标签:
9条回答
  • 2020-11-27 04:03

    In PHP 7 is to do the same in javascript

    $gen = (function() {
        yield 1;
        yield 2;
    
        return 3;
    })();
    
    foreach ($gen as $val) {
        echo $val, PHP_EOL;
    }
    
    echo $gen->getReturn(), PHP_EOL;
    

    The output is:

    1
    2
    3
    
    0 讨论(0)
  • 2020-11-27 04:04

    Well of course you can use call_user_func, but there's still another pretty simple alternative:

    <?php
    // we simply need to write a simple function called run:
    function run($f){
        $f();
    }
    
    // and then we can use it like this:
    run(function(){
        echo "do something";
    });
    
    ?>
    
    0 讨论(0)
  • 2020-11-27 04:05

    Not executed inmediately, but close to ;)

    <?php
    
    $var = (function(){ echo 'do something'; });
    $var();
    
    ?>
    
    0 讨论(0)
提交回复
热议问题