is there any alternative to a giant conditional without being a switch case?

0
    $metodo = array(
        "1"=> fazMetodo1(), //retorna algum valor
        "2"=> fazMetodo2(), //retorna algum valor
        "3"=> fazMetodo3() //retorna algum valor
        //... assim vai
    );

    $inputId = "2";

    if (array_key_exists($inputId , $metodo )) {
        $metodo[$inputId]; 
    }


        //Por switch-case
        $inputId = "2";
        switch($inputId){
            case "1":
                fazMetodo1();
                break;
            case "2":
                fazMetodo2();
                break;
            case "3":
                fazMetodo3();
                break;
        }     

The problem: As soon as array starts, all methods will return something, is there an alternative way to do it other than by switch case?

    
asked by anonymous 11.03.2016 / 16:28

1 answer

3
If the elements of $inputId represent the key of the array then use the variables as string, variables in php can call functions, see an example:

$metodo = array(
    'fazMetodo1',
    'fazMetodo2',
    'fazMetodo3',
    'fazMetodo4'
);

if (isset($metodo[$inputId]) && is_callable($metodo[$inputId])) {
    $callback = $metodo[$inputId];
    $callback(); //Chama a função
}

Prefer to use isset and is_callable to array_key_exists , so we can check if the variable exists or is null and is_callable checks to see if it is "callable".

    
11.03.2016 / 16:41