2

I have developed a new technique for my future programs to decide which function is to be fired without if/else statements. It is to create an associative array of functions and call them by a function according to argument given. I think actual representation will be better.

$_functions = array(
    "names" => function() {
        ....
    },
    "orders" => function() {
        ....
    }
);
function doLoad($toLoad) {
    global $_functions;
    $_functions[$toLoad]();
}

Now, a user has to write only:

doLoad("names");

wherever they want to print out names.

Question:

I will be creating a script and it will be distributed among other fellas to use it their way.

Is it better to do it like this way for my script? Is there any drawbacks of this technique?

ComFreek
  • 29,044
  • 18
  • 104
  • 156
Muhammad Talha Akbar
  • 9,952
  • 6
  • 38
  • 62
  • 3
    are you sure looking for an element in an array is faster than a switch? – Gianmarco Aug 24 '13 at 08:52
  • He's not searching, but doing a lookup in constant time. – Frederik Wordenskjold Aug 24 '13 at 08:56
  • 1
    Why not use an object for this? You're basically reimplementing method lookup, but in a less stable way. –  Aug 24 '13 at 08:57
  • Check out [Can you store a function in a PHP array?](http://stackoverflow.com/questions/1499862/can-you-store-a-function-in-a-php-array) – Marty McVry Aug 24 '13 at 08:59
  • @Gianmarco Hey, I ran tests for both. For my technique: http://codepad.viper-7.com/GuJqf9 and for switch http://codepad.viper-7.com/xJBz6R. Both have same loading time. These tests were done on 1 MB/s internet speed. – Muhammad Talha Akbar Aug 24 '13 at 09:27

2 Answers2

1

I don't really understand what you are looking for, but I would have done it this way, for more readability. It may also be more efficient :

function doLoadNames() {

}
function doLoadOther() {

}

function doLoad($toLoad) {
    $functionName = 'doLoad'.ucfirst($toLoad);
    if (function_exists($functionName)) {
        $functionName();
        return true;
    }
    return false;
}
Brewal
  • 8,067
  • 2
  • 24
  • 37
0

all you need is a function called call_user_func or call_user_func_array, manuals are here call_user_func, call_user_func_array

Fu Xu
  • 766
  • 2
  • 6
  • 21