GOSUB for PHP
Attention: This post is an April fool hoax! There are no plans by anybody for GOSUB or similar in PHP!
Since version 5.3 the PHP programming language finally supports the GOTO operator. GOTO is a standard construct in high-level programming languages and has a long history in paradigm of structured programming. The GOTO statement allows to solve daily programming tasks, like implementing finite state machines, very easily and comfortably. GOTO constructs raise the code quality of such implementations drastically.
PHP supports so-called labeled GOTO, in lack of forced source code line numbering. An example of how GOTO works in PHP is shown below:
<?php
$counter = 0;
main:
$counter++;
echo "I'm in main\n";
if ( $counter <= 5 )
{
goto subroutine;
}
else
{
exit;
}
subroutine:
echo "I'm in sub routine\n";
goto main;
?>
main and subroutine are labels in this simple PHP script. Inside the if statement, the script performs a jump to the label subroutine, if the $counter is not larger than 5, yet. This jump results in the execution flow to jump to line 20, where the label is declared. After printing out the text, another jump is performed, back to the main label.
As can be seen in this example, a major drawback in the PHP implementation of GOTO is that the more advanced version GOSUB is not supported, yet. The GOSUB statement allows you to return from a sub-routine right to the next statement after the jump. It allows you to simplify the code above drastically as can be seen below:
<?php
$counter = 0;
while ( $counter < 5 )
{
echo "I'm in main\n";
$counter++;
gosub subroutine;
}
subroutine:
echo "I'm in sub routine\n";
return;
?>
In this script, GOSUB is used instead of GOTO, making the main label unnecessary. The return statement after the subroutine label makes the execution flow jump right back to the next statement after the GOSUB call. Beside cleaning up the shown code, GOSUB has the drastic benefit, that it makes labeled sub-routines re-usable: The jump back is not bound to a fixed label, but returns to the place where the routine was entered.
To fix this drastic drawback against more advanced GOTO implementations, like e.g. in Basic, the PHP core developers decided to delay the release of PHP 5.3 once more. The current release candidate state of PHP 5.3 is canceled and the development team is now working on another alpha version. Due to the complex changes necessary in the parser, the stable version of PHP 5.3 can not be expected before January 2010.
Rasmus Lerdorf, the inventor of PHP, stated, that he is highly pleased to see this change coming in so straightforward. He is sure, that this is an important addition to the PHP programming language and supports the newly decided delay of version 5.3 to fix the misery. Rasmus said: "It is unacceptable that PHP is struck off by other high-level languages like Basic".
Comments