Can you store a function in a PHP array? Can you store a function in a PHP array? arrays arrays

Can you store a function in a PHP array?


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


Since PHP "5.3.0 Anonymous functions become available", example of usage:

note that this is much faster than using old create_function...

//store anonymous function in an array variable e.g. $a["my_func"]$a = array(    "my_func" => function($param = "no parameter"){         echo "In my function. Parameter: ".$param;    });//check if there is some function or methodif( is_callable( $a["my_func"] ) ) $a["my_func"]();     else echo "is not callable";// OUTPUTS: "In my function. Parameter: no parameter"echo "\n<br>"; //new lineif( is_callable( $a["my_func"] ) ) $a["my_func"]("Hi friend!");     else echo "is not callable";// OUTPUTS: "In my function. Parameter: Hi friend!"echo "\n<br>"; //new lineif( is_callable( $a["somethingElse"] ) ) $a["somethingElse"]("Something else!");     else echo "is not callable";// OUTPUTS: "is not callable",(there is no function/method stored in $a["somethingElse"])

REFERENCES:


Warning create_function() has been DEPRECATED as of PHP 7.2.0. Relying on this function is highly discouraged.

To follow up on Alex Barrett's post, create_function() returns a value that you can actually use to call the function, thusly:

$function = create_function('$echo', 'echo $echo;' );$function('hello world');