PHP Conference Fukuoka 2025

goto

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

¿Cuál es la cosa más extraña al usar goto?

Imagen proporcionada por » xkcd

El operador goto puede ser utilizado para continuar la ejecución del script en otro punto del programa. El destino es especificado por una etiqueta sensible a mayúsculas y minúsculas, seguida de dos puntos, y la instrucción goto es luego seguida de esta etiqueta. goto no está totalmente sin limitaciones. La etiqueta de destino debe estar en el mismo contexto y fichero, lo que significa que no es posible cambiar de método o función, ni ir a otra función. Asimismo, es imposible entrar en una estructura de bucle o un switch. Sin embargo, es posible salir de ellas, y el uso común es entonces utilizar goto como un break.

Ejemplo #1 Ejemplo con goto

<?php

goto a;
echo
'Foo';

a:
echo
'Bar';

?>

El ejemplo anterior mostrará :

Bar

Ejemplo #2 Ejemplo de bucle con goto

<?php
for ($i = 0, $j = 50; $i < 100; $i++) {
while (
$j--) {
if (
$j == 17) {
goto
end;
}
}
}
echo
"i = $i";
end:
echo
'j hit 17';

?>

El ejemplo anterior mostrará :

j hit 17

Ejemplo #3 Este goto no funciona

<?php
goto loop;
for (
$i = 0, $j = 50; $i < 100; $i++) {
while (
$j--) {
loop:
}
}
echo
"$i = $i";

?>

El ejemplo anterior mostrará :

Fatal error: 'goto' into loop or switch statement is disallowed in
script on line 2

add a note

User Contributed Notes 5 notes

up
61
Lollo
4 years ago
You should mention the label can't be a variable
up
36
devbyjesus at example dot com
3 years ago
the problem of goto is that it is a good feature but in a large codebase it reduces the readability of the code . that's all . i try to not use it to think about the person who is going to read after me .
up
12
georgy dot moshkin at techsponsor dot io
1 year ago
You can use goto to hide large HTML blocks without using echo():<html><body><?php if ($hide_form_and_script) { goto label_1;} ?><form action="" method="post"><!-- some HTML here --></form><script>let a='test'; // no need to escape nested quotes as with echo()// some JavaScript here</script><?php label_1: ?></body></html>
up
7
BPI
3 years ago
You can jump inside the same switch. This can be usefull to jump to default<?php$x=3;switch($x){    case 0:    case 3:        print($x);            if($x)            goto def;    case 5:        $x=6;    default:        def:        print($x);}?>
up
0
kgyt at kgyt dot eu
1 month ago
In example #2 use do-while instead:<?phpdo {    for ($i = 0, $j = 50; $i < 100; $i++) {        while ($j--) {            if ($j == 17) {                break 3;            }        }    }    echo "i = $i";} while(false);echo 'j hit 17';?>
To Top