Function as array value

前端 未结 4 1393
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-05 19:31

I can\'t seem to find anything of this, and was wondering if it\'s possible to store a function or function reference as a value for an array element. For e.g.



        
4条回答
  •  盖世英雄少女心
    2020-12-05 20:23

    Yes, you can:

    $array = array(
        'func' => function($var) { return $var * 2; },
    );
    var_dump($array['func'](2));
    

    This does, of course, require PHP anonymous function support, which arrived with PHP version 5.3.0. This is going to leave you with quite unreadable code though.

提交回复
热议问题