Search code examples
phpdynamic-function

Script to execute 1 of 2 functions randomly?


Is it possible to modify the script below so that the value of each option is a function?

<?php

$option[0] = 'html option 1';
$option[1] = 'html option 2';

echo $option[rand()%count($option)];
?>

Obviously, this doesn't work:

function get_ads_rotation(){
    $option[0] = get_ad_option1();
    $option[1] = get_ad_option2();
   echo $option[rand()%count($option)];

}

(Props to yes123 for the randomization script above)


Solution

  • Direct answer to the question: variables can store anonymous functions since PHP 5.3 only. It would be like this:

    $option[1] = function($args) { /* do something here with $args */ };
    

    However in preceding versions you could achieve something similar with call_user_func(), by storing function names in your options, and then passing the chosen option as the first argument. E.g.

    $option[1] = 'functionOne';
    // ...
    call_user_func($option[1], /* other parameters if needed */);
    

    However, it has a security hole, if the value is taken from user input.

    Hence, more secure option would be to manually call the function depending on the chosen option with a switch statement:

    switch ($option[rand()%count($option)]) {
        case 'html option 1' : functionOne(); break;
        case 'html option 2' : functionTwo(); break;
        case 'html option 3' : functionThree(); break;
        // ....
        default :  break;
    }