将函数存储为数组php的元素 [英] Store functions as elements of an array php

查看:48
本文介绍了将函数存储为数组php的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it possible store a few functions in an array by reference or by anonymous function?

例如:

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

其中fun1和fun3定义为

where fun1 and fun3 are defined as

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

推荐答案

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

As long as your PHP version is >= 5.3 you'll be able to harness anonymous functions and regular functions in your array:

function yourFunction($string){
    echo $string . " : by reference";
};

$array = array(
    'a' => function($string){
        echo $string;
    },
    'b' => 'yourFunction',
);

您可以使用 call_user_func

You can use the call_user_func or call_user_func_array functions.

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


或者作为 @Andrew也曾在评论中指出 ,您可以将其称为:


Or As @Andrew stated in the comments too, you could call it as the following:

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


如果您想了解有关这些回调方法的更多信息,请参阅


If you'd like to read more about these callback methods, it's filed under the callback pseudo-type documentation on PHP.net and it is well worth a read!

这篇关于将函数存储为数组php的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆