LABEL in PHP ’switch – case’ statement (almost GOTO)
Yeah i know, every good programmer loves ‘goto’ statement ;) I did not used it jet, but it works well i think, and was just written by me for some pal.
Code below uses the WHILE loop with a SWITCH statement to generate jumps between needed CASE: conditions. But You have to watch for the $condition or set emergency counter ($ctr) to avoid endless loop.
$code = 304; // start with some example code
$fork_question = false; // some IF to fork
$condition = false; // break if $condition is set or just secure the loop
$ctr = 0; // exit help counter or needed loops count (5 is set for example)
while( !$condition || $ctr == 5 ) {
switch ( $code ) {
case 1:
echo "in case 1<br />";
break;
case 304:
{
echo "in case 304<br />";
if ($fork_question)
{
echo "never here<br />";
}
else
{
echo "Try to jump to 'Label' 404 code<br />";
$code = 404; // set the new code - our LABEL jump
break 1;
}
}
case 390:
echo "in case 390<br />";
break;
case 404:
echo "in case 404<br />";
$condition = true; // !
break;
default:
{
echo "DEFAULT<br />";
break;
}
}
$ctr++;
echo "Loop: ".$ctr."<br />";
}
echo "end<br />";
exit;
Please use it free as always.
That’s not a goto, that’s a finite state machine. The value of $code defines the current state at any given moment.
JarFil
September 9, 2008 at 10:12
The purpose was to create [goto - like] mechanism for specified problem and it’s done. And maybe it is FSM.
The problem was found at: http://forum.php.pl/index.php?showtopic=97619&hl=
Unfortunately in Polish language
savride
September 9, 2008 at 13:10