Array instead of switch-case in php
First of all, be warned, this article has no pratical relevance. It even might guide you to bad code. But this week it just popped into my mind that I could use an array instead of a switch-case construct. So see how we can do this. This is the example for the switch in the php manual.
switch ($i) {
case 0:
echo "i equals 0";
break;
case 1:
echo "i equals 1";
break;
case 2:
echo "i equals 2";
break;
}
Now I'm able to implement this in a array, for that I put the code for every case statement in a arrayfield Afterwards I can access the field over the parameter and execute the code in it with eval.Here's the example: (Take care to not forget the semicolon in the code string)$case[0] = "echo \"i equals 0\";";Looks pretty, but what to do if you have to do the default statment. Nothing easier then that, we just have to look if eval goes ok and if not we do something after AND-short circuit:
$case[1] = "echo \"i equals 1\";";
$case[2] = "echo \"i equals 2\";";
eval($case[$i]);
eval($case[$i]) === false && print("default");comments
You could offer classes in "How to program without control flow statements just by using eval(), || and &&" :-)
add a comment
The Trackback URL to this comment is:
http://leo.freeflux.net/blog/plugin=trackback(2538).xml
This blog is gravatar enabled.
Your email adress will never be published.
Comment spam will be deleted!






I hope your new framework doesn't contain such "creative" programming :)