Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
153 views
in Technique[技术] by (71.8m points)

Can you store a function in a PHP array?

e.g.:

$functions = array(
  'function1' => function($echo) { echo $echo; }
);

Is this possible? What's the best alternative?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The recommended way to do this is with an anonymous function:

$functions = [
  'function1' => function ($echo) {
        echo $echo;
   }
];

If you want to store a function that has already been declared then you can simply refer to it by name as a string:

function do_echo($echo) {
    echo $echo;
}

$functions = [
  'function1' => 'do_echo'
];

In ancient versions of PHP (<5.3) anonymous functions are not supported and you may need to resort to using create_function (deprecated since PHP 7.2):

$functions = array(
  'function1' => create_function('$echo', 'echo $echo;')
);

All of these methods are listed in the documentation under the callable pseudo-type.

Whichever you choose, the function can either be called directly (PHP ≥5.4) or with call_user_func/call_user_func_array:

$functions['function1']('Hello world!');

call_user_func($functions['function1'], 'Hello world!');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...