"David Otton" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > On 22 Feb 2003 03:28:22 -0000, you wrote: > > >Let's say I need to take one of 20 actions depending on a form selection. I > >could use a switch statement with 20 cases, but I could also do something > >like: > > > >// Pretend this comes from a form > >$formchoice = "mars"; > > > > > >$response = array( > > "mars" => "go_mars()", > > "mercury" => "go_mercury()", > > "earth" => "go_earth()"); > > > >foreach ($response as $choice => $action) > >{ > > if (strtoupper($formchoice) == strtoupper($choice)) > > { > > eval("$action;"); > > } > >} > > > >But are there even better ways? > > $formchoice = "mars"; > > go_planet ($formchoice); > > Keep the high-levels of the script as simple as possible, push the > complexity down into functions where it's hidden from view. > > Maybe go_planet() just calls go_mercury(), go_venus(), etc., or, more > likely, there's enough shared-functionality for only go_planet() to be > necessary. > > Either way, you've replaced 11 lines in the main body of your script > with 1 line, and the next person to deal with your code will be > grateful.
:) I think if You use go_planet($choice), the problem will still remain, bacause that "big switch" should reside in go_planet() func, so we come to the start of the problem. (of course if we should take different actions depending on the choice). I think the one way is like described in upper message, to use variable names of functions. Ok, that's nice, but I personally wouldnt use this as it is very language specific (of course we could regard it like pointers to funcs in C :)), and I think doing many such tricks of this increases the complexity of your code and so on. I'd use OO principals for that, making an object for each planet, and each shoud have a method like go_planet() for THIS particular planet, as they all this objects would inplement the interface with the same method (of course u may not do that inheritance in PHP explicitely), So u'd have smth like this: $response = array( > > "mars" => object, //mars object > > "mercury" => object, //mercury object > > "earth" => " object, //earthobject and if your choice is "mars", u'd call $response['mars']->go_planet(); Its a known OO principal for avoiding switch'es and if's, and PHP is a nice OO style language, so doing in OO like this should give valuable practice for migrating to any other "real" OO language. Sorry, if wrong, Mark. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php