Php – An alternative to an array of functions

functional programmingfunctionsPHP

I'm programming an app (php) which requires a very long list of similar yet different functions, which are being called by a set of keys:

$functions = [
    "do this" => function() {
        // does this
    },
    "do that" => function() {
        // does that
    }
] 
etc.

I've chosen to place the similar functions in an array because they are not similar enough – getting the same result with one big function which is full of conditional statements isn't gonna work. And I do need to be able to call them only by key, for example:

$program = ["do this", "do that", "do this"];
foreach ($program as $k => $v) {
    $functions[$v]();
}

Thing is this functions-array structure is causing many problems, for example I'm having a hard time calling one array function from within another array function, e.g. this doesn't work:

"do that" => function() {
    $functions["do this"]();
}

nor this:

"do that" => function() {
    global $functions;
    $functions["do this"]();
}

or this:

"do that" => function($functions) {
    $functions["do this"]();
}

$functions["do that"]($functions);

I guess I could have one giant function with a long switch statement:

function similar_functions($key) {
    switch ($key) {
        case "do this":
            // does this
        break;
        case "do that":
            // does that
        break;
    }
}

But that doens't really seem like good practice. Or maybe it is?

So, what are my alternatives? Should I go with the switch structure? Or is there another, better solution?

Best Answer

Expanding on @lortabac's comment:

You can pass around pointers to functions just by passing the function name, e.g.:

function fn1()
{
    // ...
}

function fn2($fn)
{
    $fn();
}

fn2(fn1);

So you should be able to populate your array like so:

$functions = [
    "do this" => fn1,
    "do that" => fn2
]

or, if you want to be able to have the functions be able to call each other using the references set up in the array, you can define the array first, then write the functions, then set the references to the functions in the array after that.

Related Topic