PHP – switch statement vs. function dispatching

When you start having too many cases in your switch statement, it might be worth looking into using a function lookup. This is possible in all languages where functions are first class citizens…

<?php
$post = "hello";
$info = "3.1415";
//-----------------------------------------------------------
// Version 1 - using a switch statement
//-----------------------------------------------------------

switch ($post) {
    case "hey": {
        print("I've been called with $info\n");
        break;
    }

    case "there": {
        print("I've been called with $info\n");
        break;
    }

    case "hello": {
        print("I've been called with $info\n");
        break;
    }

    default: {
        print("shouldn't have gotten here\n");
    }
}

//-----------------------------------------------------------
// version 2 - same thing using a dictionary of functions
//-----------------------------------------------------------

$funcArray = Array(
    "hey" => function ($param) {
        print("I've been called with $param\n");
    },
    "there" => function ($param) {
        print("I've been called with $param\n");
    },
    "hello" => function ($param) {
        print("I've been called with $param\n");
    }
);

// The data driven invocation of the correct function:

if (isset($funcArray[$post])) {
    // Invoke the relevant function if the string is found
    $funcArray[$post]($info);
}
else {
    print("shouldn't have gotten here\n");
}
?>

Leave a Reply

Your email address will not be published. Required fields are marked *