using variables for the cases and a function for a switch?

16,557

Solution 1

Using a function in the switch is OK : the function will be called, and will return a value -- which is the one that will be used for the case.

It's exactly the same as writing :

$my_var = function_foo($bar,$bar2);
switch ($my_var) {
    // ...
}

Even if I prefer using a variable, so the code is easier to read.


And using variables in the case is something you don't see often ; but it works fine too ;-)

Quoting the manual page of switch :

The case expression may be any expression that evaluates to a simple type, that is, integer or floating-point numbers and strings.

So, your code will work, as long as $fu and $fubar contain simple-type values.


Using a variable as a case value not often done (as far as I can tell from the code I read), probably because some other languages don't allow that (for instance, C doesn't allow that ; and the switch/case structure is borrowed from C) ; but it works :

$a = 1;
$b = 2;
switch (1) {
    case $a: echo 'a'; break;
    case $b: echo 'b'; break;
}

Will output :

a

Solution 2

Never tried a function as parameter to the switch, not sure (You should give it a try), however you can first store function return value in some variable and use that in switch eg:

$return_value = function_foo($bar, $bar2);

switch ($return_value) {
case $fu:
    *Do Stuff*
    break;
case $fubar:
    *Do Other Stuff*
    break;
}

Solution 3

According to the manual, a PHP switch statement is exactly like a series of if/else if statements (if every case ends with break). That means your technique should work. As long as the function names and variable names are readable, I can't think of any problems with it.

In some other languages, the switch statement is actually a performance improvement over if/else if statements, so you need to know the case values at compile time. It doesn't look like PHP does that kind of thing.

Solution 4

Its posibble yes and its called lambda, which are hidden functions

$lambda = function($a, $b) {
    return $a * $b;
};


$return_value = function foo($bar, $bar2){ return $logic }

switch ($lambda(2,4)) {
case $fu:
    *Do Stuff*
    break;
case $fubar:
    *Do Other Stuff*
    break;
}
Share:
16,557
aslum
Author by

aslum

Gamer, Librarian, Web designer

Updated on June 14, 2022

Comments

  • aslum
    aslum almost 2 years

    In PHP I'd like to do this:

    switch (function_foo($bar,$bar2)) {
    case $fu:
        *Do Stuff*
        break;
    case $fubar:
        *Do Other Stuff*
        break;
    }
    

    Is this a terrible idea? Will it work?