Function as array value

前端 未结 4 1395
佛祖请我去吃肉
佛祖请我去吃肉 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:27

    check out PHP's call_user_func. consider the below example.

    consider two functions

    function a($param)
    {
        return $param;
    }
    
    function b($param)
    {
        return $param;
    }
    
    
    $array = array('a' => 'first function param', 'b' => 'second function param');
    

    now if you want to execute all the function in a sequence you can do it with a loop.

    foreach($array as $functionName => $param) {
        call_user_func($functioName, $param);
    }
    

    plus array can hold any data type, be it function call, nested arrays, object, string, integer etc. etc.

提交回复
热议问题