Store functions as elements of an array php

一笑奈何 提交于 2021-02-11 11:47:06

问题


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

For example:

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

where fun1 and fun3 are defined as

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

回答1:


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',
);

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');

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!




回答2:


Yes, you can do that, however you can't store the function as literal, but instead you have to refer to it by its name:

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

foreach ($array as $fun) {
    $fun();
}

Note that because it's by name, you'll have to use the fully qualified name should your function happen to be in a namespace; e.g. 'foo\bar\baz'.




回答3:


Here is an example, with anonymous function and by reference

 $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!');
?>


来源:https://stackoverflow.com/questions/37557538/store-functions-as-elements-of-an-array-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!