goto

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

L'operatore goto può essere utilizzato per saltare ad un altra sezione nel programma. Il punto d'arrivo è specificato da un'etichetta seguita dai due punti, e l'istruzione è data con goto seguito dall'etichetta desiderata. Questo non è un goto completamente libero da restrizioni. L'etichetta deve essere all'interno dello stesso file e contesto, ciò significa che non si può saltare fuori da una funzione o metodo, e neanche saltare all'interno di un'altra funzione. Inoltre non si può saltare all'interno di qualsiasi loop o struttura di switch. Si può saltarne fuori, e un caso comune è l'utilizzo di goto al posto di un break multilivello.

Example #1 esempio d'uso di goto

<?php
goto a;
echo
'Foo';

a:
echo
'Bar';
?>

Il precedente esempio visualizzerà:

Bar

Example #2 Esempio di loop 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';
?>

Il precedente esempio visualizzerà:

j hit 17

Example #3 Questo non funziona

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

Il precedente esempio visualizzerà:

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

Nota:

L'operatore goto è disponibile dal PHP 5.3.

Qual è la cosa peggiore che può succedere quando si usa goto?
Image gentilmente fornita da » xkcd

add a note

User Contributed Notes 4 notes

up
56
Lollo
4 years ago
You should mention the label can't be a variable
up
34
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
10
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
8
BPI
2 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);}?>
To Top