Is there any alternative to a giant parole other than by switch case?

Asked

Viewed 84 times

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: Once array starts, all methods will return something, there is an alternative way to do it other than by switch case?

  • What do you mean by "giant parole" (speaking of quantities, of course)?

  • This, if I have a switch with many cases, there is another alternative?

  • Explain better what your problem is. The alternative you have already given. Otherwise it has a huge gambit, so it is better not to do.

  • I thought there was a better alternative, the problem is that it will run all methods as soon as array is started (would that be the gambiarra?), rs

1 answer

3


If the elements of $inputId represent the array key so use variables like 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 the is_callable at the array_key_exists, then we can verify if the variable exists or is null and the is_callable checks if it is "calling".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.