Is Goto in PHP Evil

Is GOTO in PHP evil?

Unless you are programming in assembler, GOTO should always be treated the same way as the life vest of the airplanes: it is good to have them available, but if you need to use them it means that you are in big trouble.

Is GOTO a good practice? (in this php particular case?)

The short answers why GOTO is a bad idea: readability suffers. Consider this:

<?php require_once("registration/include/membersite_config.php"); ?>
<!DOCTYPE html>
<html lang="en">
<head><?php include_once("parts/head.php"); ?></head>
<body><div id="footerfix">
<?php include_once("parts/header.php"); ?>
<div class="container">
<div class="hero-unit">
<?php
if(isset($_GET['i'])){ unlink("users/thumbs/".$_SESSION["user_code"].".jpg"); header('Location: profile.php?i=mycv');}
if(isset($_FILES['avatar']['tmp_name'])){
$file_ext = end(explode('.',$_FILES['avatar']['name']));
if(in_array($file_ext,array('jpg','jpeg','png','gif'))==false){
echo("<h2>Error!</h2><p>Your profile photo have to be a picture file.</p>");
}
else {
$src_size=getimagesize($_FILES['avatar']['tmp_name']);
if($src_size['mime']=='image/jpeg') {
$src_img=imagecreatefromjpeg($_FILES['avatar']['tmp_name']);
} elseif($src_size['mime']=='image/png') {
$src_img=imagecreatefrompng($_FILES['avatar']['tmp_name']);
} elseif($src_size['mime']=='image/gif') {
$src_img=imagecreatefromgif($_FILES['avatar']['tmp_name']);
} else {
echo("<h2>Error!</h2><p>Incorrect file format.</p>");
}
if(!empty($src_img)) {
$thumb_w = 150;
if($src_size[0]<=$thumb_w){
$thumb=$src_img;
}else{
$new_size[0] = $thumb_w;
$new_size[1] = ($src_size[1]/$src_size[0])*$thumb_w;
$thumb=imagecreatetruecolor($new_size[0],$new_size[1]);
imagecopyresampled($thumb,$src_img,0,0,0,0,$new_size[0],$new_size[1],$src_size[0],$src_size[1]);
}
imagejpeg($thumb,"users/thumbs/".$_SESSION["user_code"].".jpg");
//header('Location: profile.php?i=mycv');
echo('<h2>Ready!</h2><p>Your profile picture is updated. <a href="profile.php">Go back</a>.</p>');
}
}
}
?>
</div></div>
<?php include_once("parts/footer.php"); ?>
</div>
</body>
</html>

Anyway, you should consider separating your template from logic (google "MVC") and use at least functions for complex operations.

What are the valid use cases of goto in PHP?

One possible use (that can however be be implemented using other means) is implementation of a finite state machine.

use goto inside function php

You cannot goto outside of a function I believe: http://php.net/manual/en/control-structures.goto.php

Direct Quote:
This is not a full unrestricted goto. The target label must be within the same file and context, meaning that you cannot jump out of a function or method, nor can you jump into one.

This might have to do with the fact that php is parsed and jumping out of a function will cause a memory leak or something because it was never properly closed.
Also as everyone else said above, really you don't need a goto. You can just return different values from the function and have a condition for each. Goto is just super bad practice for modern coding (acceptable if you are using basic).

Example:

function foo(a) {
if (a==1) {
return 1;
} elseif (a==3) {
return 2;
} else {
return 3;
}
}

switch (foo(4)) { //easily replaceable with elseif chain
case 1: echo 'Foo was 1'; break; //These can be functions to other parts of the code
case 2: echo 'Foo was 3'; break;
case 3: echo 'Foo was not 1 or 3';
}

Why does Go have a goto statement?

When we actually check the source code of the Go standard library, we can see where gotos are actually well applied.

For example, in the math/gamma.go file, the goto statement is used:

  for x < 0 {
if x > -1e-09 {
goto small
}
z = z / x
x = x + 1
}
for x < 2 {
if x < 1e-09 {
goto small
}
z = z / x
x = x + 1
}

if x == 2 {
return z
}

x = x - 2
p = (((((x*_gamP[0]+_gamP[1])*x+_gamP[2])*x+_gamP[3])*x+_gamP[4])*x+_gamP[5])*x + _gamP[6]
q = ((((((x*_gamQ[0]+_gamQ[1])*x+_gamQ[2])*x+_gamQ[3])*x+_gamQ[4])*x+_gamQ[5])*x+_gamQ[6])*x + _gamQ[7]
return z * p / q

small:
if x == 0 {
return Inf(1)
}
return z / ((1 + Euler*x) * x)
}

The goto in this case saves us from introducing another (boolean) variable used just for control-flow, checked for at the end. In this case, the goto statement makes the code actually better to read and easier follow (quite in contrary to the argument against goto you mentioned).

Also note, that the goto statement has a very specific use-case. The language specification on goto states that it may not jump over variables coming into scope (being declared), and it may not jump into other (code-)blocks.

GOTO still considered harmful?

The following statements are generalizations; while it is always possible to plead exception, it usually (in my experience and humble opinion) isn't worth the risks.

  1. Unconstrained use of memory addresses (either GOTO or raw pointers) provides too many opportunities to make easily avoidable mistakes.
  2. The more ways there are to arrive at a particular "location" in the code, the less confident one can be about what the state of the system is at that point. (See below.)
  3. Structured programming IMHO is less about "avoiding GOTOs" and more about making the structure of the code match the structure of the data. For example, a repeating data structure (e.g. array, sequential file, etc.) is naturally processed by a repeated unit of code. Having built-in structures (e.g. while, for, until, for-each, etc.) allows the programmer to avoid the tedium of repeating the same cliched code patterns.
  4. Even if GOTO is low-level implementation detail (not always the case!) it's below the level that the programmer should be thinking. How many programmers balance their personal checkbooks in raw binary? How many programmers worry about which sector on the disk contains a particular record, instead of just providing a key to a database engine (and how many ways could things go wrong if we really wrote all of our programs in terms of physical disk sectors)?

Footnotes to the above:

Regarding point 2, consider the following code:

    a = b + 1
/* do something with a */

At the "do something" point in the code, we can state with high confidence that a is greater than b. (Yes, I'm ignoring the possibility of untrapped integer overflow. Let's not bog down a simple example.)

On the other hand, if the code had read this way:

    ...
goto 10
...
a = b + 1
10: /* do something with a */
...
goto 10
...

The multiplicity of ways to get to label 10 means that we have to work much harder to be confident about the relationships between a and b at that point. (In fact, in the general case it's undecideable!)

Regarding point 4, the whole notion of "going someplace" in the code is just a metaphor. Nothing is really "going" anywhere inside the CPU except electrons and photons (for the waste heat). Sometimes we give up a metaphor for another, more useful, one. I recall encountering (a few decades ago!) a language where

    if (some condition) {
action-1
} else {
action-2
}

was implemented on a virtual machine by compiling action-1 and action-2 as out-of-line parameterless routines, then using a single two-argument VM opcode which used the boolean value of the condition to invoke one or the other. The concept was simply "choose what to invoke now" rather than "go here or go there". Again, just a change of metaphor.

PHP and the goto statement to be added in PHP 5.3

If you're writing good PHP code, you shouldn't need to use goto. I think it's a mistake that they're adding it in, as it just leads to lazy programming.

See

http://www.procata.com/blog/archives/2004/07/29/goto-in-php/

For a good commentary on the addition of this to PHP, and also, here on stack overflow,

GOTO still considered harmful?

GOTO command in PHP?

They are not adding a real GOTO, but extending the BREAK keyword to use static labels. Basically, it will be enhancing the ability to break out of switch nested if statements. Here's the concept example I found:

<?php
for ($i = 0; $i < 9; $i++) {
if (true) {
break blah;
}
echo "not shown";
blah:
echo "iteration $i\n";
}
?>

Of course, once the GOTO "rumor" was out, there was nothing to stop some evil guys to propagate an additional COMEFROM joke. Be on your toes.

See also:

http://www.php.net/~derick/meeting-notes.html#adding-goto



Related Topics



Leave a reply



Submit