e.g.:
$functions = array( 'function1' => function($echo) { echo $echo; } );
Is this possible? What's the best alternative?
The simple answer is yes you can place function in an array. In fact, can declare variables and reference them in your function.
In PHP, an array is a data structure which allows you to store multiple elements in a single variable. These elements are stored as key-value pairs. In fact, you can use an array whenever there's a need to store a list of elements. More often than not, all the items in an array have similar data types.
PHP offers an extensive array. manipulation toolkit—over 60 functions—that lets you process arrays in almost. any way imaginable including reversing them, extracting subsets, comparing and. sorting, recursively processing, and searching them for specific values.
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 method if( is_callable( $a["my_func"] ) ) $a["my_func"](); else echo "is not callable"; // OUTPUTS: "In my function. Parameter: no parameter" echo "\n<br>"; //new line if( 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 line if( 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:
Anonymous function: http://cz1.php.net/manual/en/functions.anonymous.php
Test for callable: http://cz2.php.net/is_callable
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With