【问题标题】:Store functions as elements of an array php将函数存储为数组 php 的元素
【发布时间】:2016-06-01 00:10:28
【问题描述】:

是否可以通过引用或匿名函数将一些函数存储在数组中?

例如:

 $array = [fun1, function(){ /*do something*/ }, fun3];

其中 fun1 和 fun3 定义为

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

【问题讨论】:

    标签: php arrays function


    【解决方案1】:

    只要您的 PHP 版本是 >= 5.3,您就可以在数组中使用匿名函数和常规函数:

    function yourFunction($string){
        echo $string . " : by reference";
    };
    
    $array = array(
        'a' => function($string){
            echo $string;
        },
        'b' => 'yourFunction',
    );
    

    您可以使用call_user_funccall_user_func_array 函数。

    call_user_func($array['a'], 'I love things');
    call_user_func($array['b'], 'I love things');
    

    或者@Andrew stated in the comments也可以这样称呼它:

    $array['a']('I love things');
    $array['b']('I love things');
    

    如果您想了解更多关于这些回调方法的信息,请参阅callback pseudo-type documentation on PHP.net,非常值得一读!

    【讨论】:

    • 你不是说> 5.3吗?另外,我认为您可以直接称呼它为$array['a']('I love things'),不是吗?
    • 哈哈@Andrew 是的,我做到了!现在还为时过早:|
    【解决方案2】:

    是的,您可以这样做,但是您不能将函数存储为 literal,而是必须通过其名称来引用它:

    $array = ['fun1', function () { /*do something*/ }, 'fun3'];
    
    foreach ($array as $fun) {
        $fun();
    }
    

    请注意,由于它是按名称,因此如果您的函数恰好位于命名空间中,则必须使用完全限定名称;例如'foo\bar\baz'.

    【讨论】:

      【解决方案3】:

      这是一个例子,带有匿名函数和引用

       $test = array();
      
       $test['testFunction'] = function($message) {
        echo $message;
       };
      
      
       function show_msg($message) {
           echo $message;
       }
      
       $test['testFunction2'] = 'show_msg';
      
       call_user_func($test['testFunction'], 'Hi!');
      
       call_user_func($test['testFunction2'], 'Hello world!');
      ?>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-10-25
        • 1970-01-01
        • 2017-01-24
        • 1970-01-01
        • 2015-04-21
        • 1970-01-01
        • 2015-03-29
        • 1970-01-01
        相关资源
        最近更新 更多