Function as array value

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

    0 讨论(0)
  • 2020-12-05 20:27

    You can "reference" any function. A function reference is not a reference in the sense of "address in memory" or something. It's merely the name of the function.

    <?php
    
    $functions = array(
      'regular' => 'strlen',
      'class_function' => array('ClassName', 'functionName'),
      'object_method' => array($object, 'methodName'),
      'closure' => function($foo) {
        return $foo;
      },
    );
    
    // while this works
    $functions['regular']();
    // this doesn't
    $functions['class_function']();
    
    // to make this work across the board, you'll need either
    call_user_func($functions['object_method'], $arg1, $arg2, $arg3);
    // or
    call_user_func_array($functions['object_method'], array($arg1, $arg2, $arg3));
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-05 20:28

    PHP supports the concept of variable functions, so you can do something like this:

    function foo() { echo "bar"; }
    $array = array('fun' => 'foo');
    $array['fun']();
    

    Yout can check more examples in manual.

    0 讨论(0)
提交回复
热议问题