Vlad is Glad Vlad is Glad - 4 months ago 8x
PHP Question

Store functions as elements of an array php

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*/}


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

$array = array(
    'a' => function($echo){
        echo 'test';

You will however have to use the call_user_func or call_user_func_array functions to use them effectively.

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

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

$array['a']('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.