cortesi Fri Dec 7 18:58:06 2001 EDT Modified files: /phpdoc/it/language control-structures.xml Log: half translated by Gianluca Baldo, I will maintain it now
Index: phpdoc/it/language/control-structures.xml diff -u /dev/null phpdoc/it/language/control-structures.xml:1.7 --- /dev/null Fri Dec 7 18:58:06 2001 +++ phpdoc/it/language/control-structures.xml Fri Dec 7 18:58:06 2001 @@ -0,0 +1,1535 @@ +<?xml version="1.0" encoding="iso-8859-1"?> +<!-- EN-Revision: 1.45 Maintainer: cortesi Status: working --> + <chapter id="control-structures"> + <title>Strutture di controllo</title> + + <simpara> + Qualsiasi script PHP è costituito da una serie di istruzioni. Una istruzione + può essere un'assegnazione, una chiamata di funzione, un loop, una istruzione +condizionale + che non fa nulla (istruzione vuota). + Le istruzioni terminano con un punto e virgola. Inoltre, le istruzioni + si possono raggruppare in blocchi di istruzioni racchiudendole tra + parentesi graffa. + Un gruppo di istruzioni è, a sua volta, un'istruzione. Il presente capitolo + descrive i differenti tipi di istruzioni. + </simpara> + + <sect1 id="control-structures.if"> + <title><literal>if</literal></title> + <para> + Il costrutto <literal>if</literal> è uno delle più importanti + caratteristiche di qualsiasi linguaggio, incluso PHP. + Permette l'esecuzione condizionata di frammenti di codice. + La struttura di controllo <literal>if</literal> di PHP è simile a quella del +linguaggio C: + <informalexample> + <programlisting> +<![CDATA[ +if (espressione) + istruzione +]]> + </programlisting> + </informalexample> + </para> + <simpara> + Come descritto nel capitolo sulle espressioni, expr restituirà il + suo valore di verità. Se <replaceable>espressione</replaceable> + è &true;, PHP eseguirà l'espressione, se + è &false;, la ignorerà. + </simpara> + <para> + L'esempio che segue visualizzerà <computeroutput>a è maggiore + di b</computeroutput> se <replaceable>$a</replaceable> sarà maggiore + di <replaceable>$b</replaceable>: + <informalexample> + <programlisting role="php"> +<![CDATA[ +if ($a > $b) + print "a è maggiore di b"; +]]> + </programlisting> + </informalexample> + </para> + <para> + Spesso sarà necessario eseguire più di una istruzione + condizionale. Naturalmente non è necessario, utilizzare una singola clausola + <literal>if</literal> per ciascuna istruzione. Si possono raggruppare diverse +istruzioni + in un singolo gruppo di istruzioni. Per esemipo, il codice che segue + visualizzerà <computeroutput>a is bigger than b</computeroutput> + se <replaceable>$a</replaceable> è maggiore di <replaceable>$b</replaceable>, + e successivamente assegnerà il valore della variabile +<replaceable>$a</replaceable> + alla variabile <replaceable>$b</replaceable>: + <informalexample> + <programlisting role="php"> +<![CDATA[ +if ($a > $b) { + print "a è maggiore dib"; + $b = $a; +} +]]> + </programlisting> + </informalexample> + </para> + <simpara> + Si possono annidare indefinitamente istruzioni + <literal>if</literal>, la qual cosa fornisce piena + flessibilità per l'esecuzione di istruzioni condizionali in differenti punti del + programma. + </simpara> + </sect1> + + <sect1 id="control-structures.else"> + <title><literal>else</literal></title> + <para> + Spesso è necessario eseguire un'istruzione se una proposizione è vera + e un'altra istruzione se la proposizione è falsa. Per questo + si usa la clausola <literal>else</literal>. <literal>else</literal> + estende il costrutto <literal>if</literal> aggiungendo la possibilità + di eseguire un'istruzione se l'espressione nel ramo <literal>if</literal> + è &false;. L'esempio che segue + visualizzerà <computeroutput>a è maggiore di + b</computeroutput> se <replaceable>$a</replaceable> è maggiore di + <replaceable>$b</replaceable> e <computeroutput>a NON è maggiore + di b</computeroutput> altrimenti: + <informalexample> + <programlisting role="php"> +<![CDATA[ +if ($a > $b) { + print "a è maggiore di b"; +} else { + print "a NON è maggiore di b"; +} +]]> + </programlisting> + </informalexample> + + Il ramo <literal>else</literal> viene eseguito solo se l'espressione + nel ramo <literal>if</literal> è + &false;, e, nel caso ci fossero delle clausole + <literal>elseif</literal>, solamente se le espressioni in esse contenute fossero + anch'esse &false; (vedere <link + linkend="control-structures.elseif">elseif</link>). + + </para> + </sect1> + + <sect1 id="control-structures.elseif"> + <title><literal>elseif</literal></title> + <para> + <literal>elseif</literal>, come è facile intuire, è una combinazione + di <literal>if</literal> and <literal>else</literal>. Analogamente a + <literal>else</literal>, estende <literal>if</literal> + aggiungendo la possibilità di eseguire un'altra istruzione nel caso + in cui l'espressione contenuta nel ramo <literal>if</literal> + sia &false;. Però, a differenza + di <literal>else</literal>, si eseguirà l'istruzione alternativa + solamente se l'espressione contenuta nel ramo <literal>elseif</literal> + sarà &true;. L'esempio + che segue, visualizzerà <computeroutput>a è maggiore di + b</computeroutput>, <computeroutput>a è uguale a b</computeroutput> + oppure <computeroutput>a è minore di b</computeroutput>: + <informalexample> + <programlisting role="php"> +<![CDATA[ +if ($a > $b) { + print "a è maggiore di b"; +} elseif ($a == $b) { + print "a è uguale a b"; +} else { + print "a è minore di b"; +} +]]> + </programlisting> + </informalexample> + </para> + <simpara> + Nel medesimo blocco <literal>if</literal> possono essere presenti + più d'una clausola <literal>elseif</literal>. L'istruzione del + primo ramo <literal>elseif</literal> la cui espressione + sia &true; verrà eseguito. In PHP è possibile + scrivere 'else if' (due parole) e il significato sarà + lo stesso di 'elseif' (una sola parola). Il significato sintattico + è leggermente differente (se si ha familiarità con il linguaggio C, esso ha lo +stesso + comportamento) però al lato pratico l'effetto è + il medesimo. + </simpara> + <simpara> + L'istruzione di un ramo <literal>elseif</literal> si eseguirà solo se +l'espressione del + ramo <literal>if</literal> e le espressioni dei + rami <literal>elseif</literal> precedenti sono + &false;, e se l'espressione + del ramo <literal>elseif</literal> è + &true;. + </simpara> + </sect1> + + <sect1 id="control-structures.alternative-syntax"> + <title>Sintassi alternativa per le strutture di controllo</title> + <para> + PHP offre una sintassi alternatica per alcune delle sue strutture di controllo; + vale a dire, <literal>if</literal>, + <literal>while</literal>, <literal>for</literal>, + <literal>foreach</literal> e <literal>switch</literal>. + Fondamentalmente la sintassi alternativa consiste nel sostituire + la prima parentesi graffa con il carattere "duepunti" (:) e la seconda parentesi +graffa con + <literal>endif;</literal>, <literal>endwhile;</literal>, + <literal>endfor;</literal>, <literal>endforeach;</literal>, oppure + <literal>endswitch;</literal>, rispettivamente. + <informalexample> + <programlisting role="php"> +<![CDATA[ +<?php if ($a == 5): ?> +A é maggiore di 5 +<?php endif; ?> +]]> + </programlisting> + </informalexample> + </para> + <simpara> + Nell'esempio precedente, il blocco HTML "A = 5" è incluso nel ramo + <literal>if</literal> scritto con utilizzando la sintassi alternativa. + Il blocco HTML verrà visualizzato solamente se $a è uguale a 5. + </simpara> + <para> + La sintassi alternativa si applica anche a <literal>else</literal> e + <literal>elseif</literal>. Nell'esempio che segue si mostra come utilizzare la +sintassi alternativa + nel caso di un <literal>if</literal> con <literal>elseif</literal> e + <literal>else</literal>: + <informalexample> + <programlisting role="php"> +<![CDATA[ +if ($a == 5): + print "a è uguale a 5"; + print "..."; +elseif ($a == 6): + print "a è uguale a 6"; + print "!!!"; +else: + print "a non è uguale nè a 5 nè a 6"; +endif; +]]> + </programlisting> + </informalexample> + </para> + <para> + Vedere anche <link linkend="control-structures.while">while</link>, + <link linkend="control-structures.for">for</link>, e <link + linkend="control-structures.if">if</link> per ulteriori esempi. + </para> + </sect1> + + <sect1 id="control-structures.while"> + <title><literal>while</literal></title> + <para> + Il ciclo <literal>while</literal> è la forma di ciclo più semplice + tra quelle possibili in PHP. Si comporta come la sua controparte nel linguaggio +C. + La forma basica di un ciclo <literal>while</literal> è la seguente: + <informalexample> + <programlisting> +<![CDATA[ +while (espressione) istruzione +]]> + </programlisting> + </informalexample> + </para> + <simpara> + Il significato di un ciclo <literal>while</literal> è semplice. + Istruisce l'interprete PHP perchè esegua l'istruzione (o le istruzioni) + in esso racchiuse, ripetutamente, fintanto che l'espressionbe contenuta + nella clausola <literal>while</literal> ha valore &true;. + Il valore dell'espressione viene verificato ogni volta che il ciclo + si ripete (iterazione), così che anche se il valore dell'espressione cambia +durante + l'esecuzione dell'istruzione, il ciclo non termina fino + all'iterazione successiva. + Ovviamente, se l'espressione nella clausola <literal>while</literal> ha valore + &false; dall'inizio, l'istruzione racchiusa nel blocco non verrà eseguita nemmeno + una volta. + </simpara> + <para> + Come nel caso della struttura di controllo <literal>if</literal>, si possono +raggruppare + più istruzioni nello medesimo ciclo <literal>while</literal> + racchiudendo le istruzioni in parentesi grafa, oppure + utilizzando la sintassi alternativa: + <informalexample> + <programlisting> +<![CDATA[ +while (espressione): istruzione ... endwhile; +]]> + </programlisting> + </informalexample> + </para> + <para> + Gli esempi seguenti sono identici e entrambi visualizzano i numeri da + 1 a 10: + <informalexample> + <programlisting> +<![CDATA[ +/* esempio 1 */ + +$i = 1; +while ($i <= 10) { + print $i++; /* Il valore visualizzato è il valore della + variabile $i prima dell'incremento + (post-increment) */ +} + +/* esempio 2 */ + +$i = 1; +while ($i <= 10): + print $i; + $i++; +endwhile; +]]> + </programlisting> + </informalexample> + </para> + </sect1> + + <sect1 id="control-structures.do.while"> + <title><literal>do..while</literal></title> + <simpara> + Il ciclo <literal>do..while</literal> è simile al ciclo + <literal>while</literal>, con l'unica differenza che il valore dell'espressione + viene controllato alla fine di ogni iterazione anzichè all'inizio. + La differenza più importante rispetto a <literal>while</literal> è che + la prima iterazione di un blocco <literal>do..while</literal>verrà + sempre eseguita (il valore dell'espressione viene controllato alla fine + del ciclo), mentre non è necessariamente vero in un + ciclo <literal>while</literal> questo (il valore dell'espressione viene + controllato all'inizio del ciclo, e se tale valore è + &false; dall'inizio, l'esecuzione del ciclo + termina immediatamente). + </simpara> + <para> + È ammessa una sola sintassi per il ciclo <literal>do..while</literal>: + + <informalexample> + <programlisting role="php"> +<![CDATA[ +$i = 0; +do { + print $i; +} while ($i>0); +]]> + </programlisting> + </informalexample> + </para> + <simpara> + Il ciclo precedente verrà eseguito un'unica volta, dal momento che + alla prima iterazione, quando si controlla l'espressione, il suo valore sarà + &false; ($i non è maggiore di 0) e il ciclo di + esecuzioni, termina. + </simpara> + <para> + Chi ha utilizzato il linguaggio C conosce probabilmente un'altro modo di +utilizzare + il ciclo <literal>do..while</literal>, che permette di terminare l'esecuzione + delle istruzioni durante l'esecuzione stessa, utilizzando + <literal>do..while</literal>(0), e usando l'istruzione <link + linkend="control-structures.break"><literal>break</literal></link>. + Il codice che segue esemplifica questa possibilità: + <informalexample> + <programlisting role="php"> +<![CDATA[ +do { + if ($i < 5) { + print "i non è abbastanza grande"; + break; + } + $i *= $factor; + if ($i < $minimum_limit) { + break; + } + print "i è ok"; + + ...processa i... + +} while(0); +]]> + </programlisting> + </informalexample> + </para> + <simpara> + Non vi preoccupate se l'esempio non è sufficientemente chiaro. + Si possono scrivere ottimi programmi PHP anche senza far ricorso a questa + 'possibilità'. + </simpara> + </sect1> + + <sect1 id="control-structures.for"> + <title><literal>for</literal></title> + <para> + Il ciclo <literal>for</literal> è il ciclo più complesso tra quelli disponibili +in PHP. + Si comporta come la sua controparte nel linguaggio C. + La sintassi di un clico <literal>for</literal> è: + <informalexample> + <programlisting> +<![CDATA[ +for (expr1; expr2; expr3) istruzione +]]> + </programlisting> + </informalexample> + </para> + <simpara> + Il valore della prima espressione (<replaceable>expr1</replaceable>) viene + verificato (eseguito) una sola volta incondizionatamente all'inizio del + ciclo. + </simpara> + <simpara> + Ad ogni iterazione, + si controlla il valore di <replaceable>expr2</replaceable>. Se è + &true;, il ciclo prosegue e viene eseguita + l'istruzione (o le istruzioni) contenuta nel blocco; + se è &false;, l'esecuzione del ciclo termina. + </simpara> + <simpara> + Al termine di ogni iterazione, <replaceable>expr3</replaceable> si verifica + il valore di <replaceable>expr3</replaceable>. + </simpara> + <simpara> + Le due espressioni possono anche non essere presenti. + Se non esiste <replaceable>expr2</replaceable> significa che il ciclo deve + essere eseguito indefinitamente (PHP considera implicitamente che il + suo valore è &true;, come in C). Questa possibilità in fondo non è + utile come può sembrare perchè obbliga a terminare il ciclo utilizzando + l'istruzione <link + linkend="control-structures.break"><literal>break</literal></link> + invece di utilizzare le espressioni di verità del ciclo <literal>for</literal> + . + </simpara> + <para> + Si considerino gli esempi seguenti. In ciascun caso si visualizzeranno + i numeri da 1 a 10: + <informalexample> + <programlisting role="php"> +<![CDATA[ +/* example 1 */ + +for ($i = 1; $i <= 10; $i++) { + print $i; +} + +/* example 2 */ + +for ($i = 1;;$i++) { + if ($i > 10) { + break; + } + print $i; +} + +/* example 3 */ + +$i = 1; +for (;;) { + if ($i > 10) { + break; + } + print $i; + $i++; +} + +/* example 4 */ + +for ($i = 1; $i <= 10; print $i, $i++) ; +]]> + </programlisting> + </informalexample> + </para> + <simpara> + Naturalmente il primo esempio sembra il migliore (o + forse il quarto), ma l'uso del + ciclo <literal>for</literal> senza espressioni può essere utile + in molti casi. + </simpara> + <para> + PHP offre una sintassi alternativa (con i "punto e virgola") per i + cicli <literal>for</literal>. + <informalexample> + <programlisting> +<![CDATA[ +for (expr1; expr2; expr3): istruzione; ...; endfor; +]]> + </programlisting> + </informalexample> + </para> + <para> + Alcuni linguaggi permettono l'uso della struttura di controllo +<literal>foreach</literal> per + attraversare un array o una tabella hash. PHP 3 non premette l'uso di tale ciclo +mentre PHP 4 sì + (vedere <link + linkend="control-structures.foreach">foreach</link>). In PHP 3 è + possibile combinare <link linkend="control-structures.while">while</link> + con la funzione <function>list</function> e <function>each</function> + per ottenere la stessa funzionalià. Si veda la documentazione si queste funzioni + per ulteriori esempi. + </para> + + </sect1> + + <sect1 id="control-structures.foreach"> + <title><literal>foreach</literal></title> + <para> + PHP 4 (non PHP 3) permette l'uso della struttura di controllo +<literal>foreach</literal>, + alla stessa maniera del linguaggio Perl e altri. + <literal>foreach</literal> offre una maniera semplice di attraversare un array. +Esistono due possibili notazioni sintattiche; la seconda è + un'utile estensione della prima: + <informalexample> + <programlisting> +<![CDATA[ +foreach(array_expression as $value) istruzione +foreach(array_expression as $key => $value) istruzione +]]> + </programlisting> + </informalexample> + </para> + <simpara> + La prima attraversa l'array dato da <literal>array_expression</literal>. + Ad ogni ciclo, si assegna il valore dell'elemento corrente a +<literal>$value</literal> + e il puntatore interno avanza di una posizione (in modo tale che + al ciclo successivo l'elemento corrente sará il successivo elemento + dell'array). + </simpara> + <simpara> + La seconda esegue lo stesso ciclo con la differenza che il + valore dell'indice corrente viene assegnato ad ogni ciclo, + alla variabile <literal>$key</literal>. + </simpara> + <para> + <note> + <para> + All'inizio dell'esecuzione di un ciclo <literal>foreach</literal> + il puntatore interno viene automaticamente posizionato nella prima + posizione. Questo significa che non è necessario utilizzare la + funzione <function>reset</function> prima di un ciclo <literal>foreach</literal> + . + </para> + </note> + </para> + <para> + <note> + <para> + È importante notare che <literal>foreach</literal> opera su una copia + dell'array, pertanto il puntatore dell'array originale non viene + modificato come accade utilizzando la funzione <function>each</function> + e le modifiche agli elementi dell'array non + appaiono nell'array originale. + </para> + </note> + </para> + <note> + <para> + <literal>foreach</literal> non offre la possibilità di annullare la generazione + di messaggi d'errore utilizzando il carattere '@'. + </para> + </note> + <para> + Avete probabilmente notato che i due cicli seguenti sono identici da un + punto di vista funzionale: + <informalexample> + <programlisting role="php"> +<![CDATA[ +reset ($arr); +while (list(, $value) = each ($arr)) { + echo "Valore: $value<br>\n"; +} + +foreach ($arr as $value) { + echo "Valore: $value<br>\n"; +} +]]> + </programlisting> + </informalexample> + Allo stesso modo i due cicli seguenti sono identici: + <informalexample> + <programlisting role="php"> +<![CDATA[ +reset ($arr); +while (list($key, $value) = each ($arr)) { + echo "Key: $key; Valore: $value<br>\n"; +} + +foreach ($arr as $key => $value) { + echo "Key: $key; Valore: $value<br>\n"; +} +]]> + </programlisting> + </informalexample> + </para> + <para> + Di seguito, altri esempi per mostrare possibili utilizzi: + <informalexample> + <programlisting role="php"> +<![CDATA[ +/* foreach example 1: value only */ + +$a = array (1, 2, 3, 17); + +foreach ($a as $v) { + print "Valore corrente of \$a: $v.\n"; +} + +/* foreach example 2: value (with key printed for illustration) */ + +$a = array (1, 2, 3, 17); + +$i = 0; /* for illustrative purposes only */ + +foreach($a as $v) { + print "\$a[$i] => $v.\n"; +} + +/* foreach example 3: key and value */ + +$a = array ( + "one" => 1, + "two" => 2, + "three" => 3, + "seventeen" => 17 +); + +foreach($a as $k => $v) { + print "\$a[$k] => $v.\n"; +} + +/* foreach example 4: multi-dimensional arrays */ + +$a[0][0] = "a"; +$a[0][1] = "b"; +$a[1][0] = "y"; +$a[1][1] = "z"; + +foreach($a as $v1) { + foreach ($v1 as $v2) { + print "$v2\n"; + } +} + +/* foreach example 5: dynamic arrays */ + +foreach(array(1, 2, 3, 4, 5) as $v) { + print "$v\n"; +} +]]> + </programlisting> + </informalexample> + </para> + </sect1> + + <sect1 id="control-structures.break"> + <title><literal>break</literal></title> + <simpara> + <literal>break</literal> termina l'esecuzione di una struttura + <literal>for</literal>, <literal>foreach</literal> + <literal>while</literal>, <literal>do..while</literal> o + <literal>switch</literal>. + </simpara> + <simpara> + <literal>break</literal> accetta un argomento opzionale che definisce, + nel caso di cicli annidati, il livello del ciclo che è da + interrompere. + </simpara> + <para> + <informalexample> + <programlisting role="php"> +<![CDATA[ +$arr = array ('one', 'two', 'three', 'four', 'stop', 'five'); +while (list (, $val) = each ($arr)) { + if ($val == 'stop') { + break; /* Si può anche usare 'break 1;'. */ + } + echo "$val<br>\n"; +} + +/* Uso dell'argomento opzionale. */ + +$i = 0; +while (++$i) { + switch ($i) { + case 5: + echo "At 5<br>\n"; + break 1; /* Interrompe solo awitch. */ + case 10: + echo "At 10; quitting<br>\n"; + break 2; /* Interrompe switch e while. */ + default: + break; + } +} +]]> + </programlisting> + </informalexample> + </para> + </sect1> + + <sect1 id="control-structures.continue"> + <title><literal>continue</literal></title> + <simpara> + <literal>continue</literal> si utilizza per interrompere l'esecuzione + del ciclo corrente e continuare con l'esecuzione + all'inizio del ciclo successivo. + </simpara> + <simpara> + <literal>continue</literal> accetta un argomento numerico opzionale + che definisce, nel caso di cicli annidati, il numero di cicli da interrompere + e a cui iniziare l'esecuzione dell'iterazione successiva. + </simpara> + <para> + <informalexample> + <programlisting role="php"> +<![CDATA[ +while (list ($key, $value) = each ($arr)) { + if (!($key % 2)) { // skip odd members + continue; + } + do_something_odd ($value); +} + +$i = 0; +while ($i++ < 5) { + echo "Outer<br>\n"; + while (1) { + echo " Middle<br>\n"; + while (1) { + echo " Inner<br>\n"; + continue 3; + } + echo "This never gets output.<br>\n"; + } + echo "Neither does this.<br>\n"; +} +]]> + </programlisting> + </informalexample> + </para> + </sect1> + + <sect1 id="control-structures.switch"> + <title><literal>switch</literal></title> + <simpara> + <literal>switch</literal> è simile a una serie di + IF sulla stessa espressione. In molti casi può essere + necessario confrontare una variabile (o espressione) con differenti + valori ed eseguire un differente blocco di istruzioni a seconda + del valore di detta variabile. Questo è esattamente quello che fa la struttura + di controllo <literal>switch</literal>. + </simpara> + <para> + Gli esempi seguenti mostrano due maniere differenti di scrivere + la stessa cosa, uno utilizzando una serie di <literal>if</literal>, + l'altro utilizzando <literal>switch</literal> + : + <informalexample> + <programlisting role="php"> +<![CDATA[ +if ($i == 0) { + print "i equals 0"; +} +if ($i == 1) { + print "i equals 1"; +} +if ($i == 2) { + print "i equals 2"; +} + +switch ($i) { + case 0: + print "i equals 0"; + break; + case 1: + print "i equals 1"; + break; + case 2: + print "i equals 2"; + break; +} +]]> + </programlisting> + </informalexample> + </para> + <para> + È importante somprendere esattamente come viene eseguita la + clausola <literal>switch</literal> per evitare errori. + Un'istruzione <literal>switch</literal> esegue linea dopo linea + le istruzioni in essa contenuta. + Solamente quando incontra una clausola <literal>case</literal> + il cui valore è uguale al valore della viariabile, PHP inizia ad + eseguire le istruzioni contenute nel blocco case. + PHP continua l'esecuzione delle istruzioni fino alla termine del + blocco <literal>switch</literal>, o quando incontra un'istruzione + <literal>break</literal>. Se non esiste alcuna + istruzione <literal>break</literal> al termine di un blocco case + PHP continuerà l'esecuzione le istruzioni del blocco case successivo. + Per esempio: + <informalexample> + <programlisting role="php"> +<![CDATA[ +switch ($i) { + case 0: + print "i è uguale a 0"; + case 1: + print "i è uguale a 1"; + case 2: + print "i è uguale a 2"; +} +]]> + </programlisting> + </informalexample> + </para> + <simpara> + In questo caso se $i è uguale a 0, PHP eseguirà tutte le + istruzioni contenute nei blocchi case. Se $i è uguale a 1, + PHP eseguirà le istruzioni degli ultimi due blocchi case e + solamente se $i è uguale a 2 otterremo il risultato voluto + e si visualizzerà solo '$i è uguale a 2'. + Pertanto è importante non dimenticare l'istruzione <literal>break</literal> + (anche se in alcuni casi potrà essere necessario non utilizzarla). + </simpara> + <simpara> + In un'istruzione <literal>switch</literal>, la condizione in parentesi + viene valutata una sola volta e il risultato viene confrontato con + ciascun ramo <literal>case</literal>. Utilizzando <literal>elseif</literal>, + la ondizione viene valutata una seconda volta. Se tale condizione è più + complessa di un semplice confronto e/o è in un ciclo piuttosto pesante, + l'uso di <literal>switch</literal> dovrebbe garantire un minor tempo di +esecuzione. + </simpara> + <para> + Un blocco case può anche non contenere istruzioni, nel qual caso + il controllo passa semplicemente al successivo blocco case. + <informalexample> + <programlisting role="php"> +<![CDATA[ +switch ($i) { + case 0: + case 1: + case 2: + print "i is less than 3 but not negative"; + break; + case 3: + print "i is 3"; +} +]]> + </programlisting> + </informalexample> + </para> + <para> + Un blocco case speciale è il il blocco case di default. + Uguagli tutte le condizioni non uguagliate nei blocchi case + precedenti e dev'essere l'ultimo blocco <literal>case</literal> statement. Per +esempio: + <informalexample> + <programlisting role="php"> +<![CDATA[ +switch ($i) { + case 0: + print "i è uguale a 0"; + break; + case 1: + print "i è uguale a 1"; + break; + case 2: + print "i è uguale a 2"; + break; + default: + print "i non è ugluale a 0, 1 o 2"; +} +]]> + </programlisting> + </informalexample> + </para> + <para> + L'espressione in un ramo case <literal>case</literal> può essere + qualsiasi espressione il cui valore sarà di tipo intero, decimale, + numerico e stringa. Array e oggetti (objects) non sono ammessi + a meno che non siano dereferenziati a un tipo di dato semplice tra quelli +precedentemente elencati. + </para> + <para> + Come per altre strutture di controllo è possibile utilizzare una sintassi + alternativa. Si veda + <link linkend="control-structures.alternative-syntax">Sintassi alternativa per le +strutture di controllo</link> + per ulteriori esempi. + <informalexample> + <programlisting role="php"> +<![CDATA[ +switch ($i): + case 0: + print "i è uguale a 0"; + break; + case 1: + print "i è uguale a 1"; + break; + case 2: + print "i è uguale a 2"; + break; + default: + print "i non è uguale a 0, 1 o 2"; +endswitch; +]]> + </programlisting> + </informalexample> + </para> + </sect1> + + <sect1 id="control-structures.declare"> + <title><literal>declare</literal></title> + <para> + Il costrutto <literal>declare</literal> si usa per definire + direttive di esecuzione per blocchi di istruzioni. + La sintassi è simile alla + sintassi di altre strutture di controllo: + <informalexample> + <programlisting> +<![CDATA[ +declare (direttiva) istruzione +]]> + </programlisting> + </informalexample> + </para> + <para> + The <literal>directive</literal> section allows the + behavior of the <literal>declare</literal> block to + be set. + Currently only one directive is recognized: the + <literal>ticks</literal> directive. (See below for more + information on the + <link linkend="control-structures.declare.ticks">ticks</link> + directive) + </para> + <para> + The <literal>statement</literal> part of the + <literal>declare</literal> block will be executed - how + it is executed and what side-effects occur during execution + may depend on the directive set in the + <literal>directive</literal> block. + </para> + <sect2 id="control-structures.declare.ticks"> + <title>Ticks</title> + <para>A tick is an event that occurs for every + <replaceable>N</replaceable> low-level statements executed + by the parser within the <literal>declare</literal> block. + The value for <replaceable>N</replaceable> is specified + using <literal>ticks=<replaceable>N</replaceable></literal> + within the <literal>declare</literal> blocks's + <literal>directive</literal> section. + </para> + <para> + The event(s) that occurs on each tick is specified using the + <function>register_tick_function</function>. See the example + below for more details. Note that more than one event can occur + for each tick. + </para> + <para> + <example> + <title>Profile a section of PHP code</title> + <programlisting role="php"> +<![CDATA[ +<pre> +<?php +// A function that records the time when it is called +function profile ($dump = FALSE) +{ + static $profile; + + // Return the times stored in profile, then erase it + if ($dump) { + $temp = $profile; + unset ($profile); + return ($temp); + } + + $profile[] = microtime (); +} + +// Set up a tick handler +register_tick_function("profile"); + +// Initialize the function before the declare block +profile (); + +// Run a block of code, throw a tick every 2nd statement +declare (ticks=2) { + for ($x = 1; $x < 50; ++$x) { + echo similar_text (md5($x), md5($x*$x)), "<br>"; + } +} + +// Display the data stored in the profiler +print_r (profile (TRUE)); +?> +</pre> +]]> + </programlisting> + </example> + The example profiles the PHP code within the 'declare' + block, recording the time at which every second low-level + statement in the block was executed. This information can + then be used to find the slow areas within particular + segments of code. This process can be performed using other + methods: using ticks is more convenient and easier to + implement. + </para> + <simpara> + Ticks are well suited for debugging, implementing simple + multitasking, backgrounded I/O and many other tasks. + </simpara> + <simpara> + See also <function>register_tick_function</function> and + <function>unregister_tick_function</function>. + </simpara> + </sect2> + </sect1> + + <sect1 id="function.require"> + <title><function>require</function></title> + <simpara> + The <function>require</function> statement replaces itself with + the specified file, much like the C preprocessor's + <literal>#include</literal> works. + </simpara> + <simpara> + If "URL fopen wrappers" are enabled in PHP (which they are in the + default configuration), you can specify the file to be + <function>require</function>ed using an URL instead of a local + pathname. See <link linkend="features.remote-files">Remote + files</link> and <function>fopen</function> for more information. + </simpara> + <simpara> + An important note about how this works is that when a file is + <function>include</function>ed or <function>require</function>ed, + parsing drops out of PHP mode and into HTML mode at the beginning + of the target file, and resumes PHP mode again at the end. For + this reason, any code inside the target file which should be + executed as PHP code must be enclosed within <link + linkend="language.basic-syntax.phpmode">valid PHP start and end + tags</link>. + </simpara> + <simpara> + <function>require</function> is not actually a function in PHP; + rather, it is a language construct. It is subject to some + different rules than functions are. For instance, + <function>require</function> is not subject to any containing + control structures. For another, it does not return any value; + attempting to read a return value from a + <function>require</function> call results in a parse error. + </simpara> + <simpara> + Unlike <function>include</function>, <function>require</function> + will <emphasis>always</emphasis> read in the target file, + <emphasis>even if the line it's on never executes</emphasis>. If + you want to conditionally include a file, use + <function>include</function>. The conditional statement won't + affect the <function>require</function>. However, if the line on + which the <function>require</function> occurs is not executed, + neither will any of the code in the target file be executed. + </simpara> + <simpara> + Similarly, looping structures do not affect the behaviour of + <function>require</function>. Although the code contained in the + target file is still subject to the loop, the + <function>require</function> itself happens only once. + </simpara> + <para> + This means that you can't put a <function>require</function> + statement inside of a loop structure and expect it to include the + contents of a different file on each iteration. To do that, use an + <function>include</function> statement. + <informalexample> + <programlisting role="php"> +<![CDATA[ +require ('header.inc'); +]]> + </programlisting> + </informalexample> + </para> + <simpara> + When a file is <function>require</function>ed, the code it + contains inherits the variable scope of the line on which the + <function>require</function> occurs. Any variables available at + that line in the calling file will be available within the called + file. If the <function>require</function> occurs inside a + function within the calling file, then all of the code contained + in the called file will behave as though it had been defined + inside that function. + </simpara> + <para> + If the <function>require</function>ed file is called via HTTP + using the fopen wrappers, and if the target server interprets the + target file as PHP code, variables may be passed to the + <function>require</function>ed file using an URL request string as + used with HTTP GET. This is not strictly speaking the same thing + as <function>require</function>ing the file and having it inherit + the parent file's variable scope; the script is actually being run + on the remote server and the result is then being included into + the local script. + <informalexample> + <programlisting role="php"> +<![CDATA[ +/* This example assumes that someserver is configured to parse .php + * files and not .txt files. Also, 'works' here means that the variables + * $varone and $vartwo are available within the require()ed file. */ + +/* Won't work; file.txt wasn't handled by someserver. */ +require ("http://someserver/file.txt?varone=1&vartwo=2"); + +/* Won't work; looks for a file named 'file.php?varone=1&vartwo=2' + * on the local filesystem. */ +require ("file.php?varone=1&vartwo=2"); + +/* Works. */ +require ("http://someserver/file.php?varone=1&vartwo=2"); + +$varone = 1; +$vartwo = 2; +require ("file.txt"); /* Works. */ +require ("file.php"); /* Works. */ +]]> + </programlisting> + </informalexample> + </para> + <simpara> + In PHP 3, it is possible to execute a <literal>return</literal> + statement inside a <function>require</function>ed file, as long as + that statement occurs in the global scope of the + <function>require</function>ed file. It may not occur within any + block (meaning inside braces ({}). In PHP 4, however, this ability + has been discontinued. If you need this functionality, see + <function>include</function>. + </simpara> + <simpara> + See also <function>include</function>, <function>require_once</function>, + <function>include_once</function>, <function>readfile</function>, + and <function>virtual</function>. + </simpara> + </sect1> + + <sect1 id="function.include"> + <title><function>include</function></title> + <simpara> + The <function>include</function> statement includes and evaluates + the specified file. + </simpara> + <simpara> + If "URL fopen wrappers" are enabled in PHP (which they are in the + default configuration), you can specify the file to be + <function>include</function>ed using an URL instead of a local + pathname. See <link linkend="features.remote-files">Remote + files</link> and <function>fopen</function> for more information. + </simpara> + <simpara> + An important note about how this works is that when a file is + <function>include</function>ed or <function>require</function>ed, + parsing drops out of PHP mode and into HTML mode at the beginning + of the target file, and resumes again at the end. For this reason, + any code inside the target file which should be executed as PHP + code must be enclosed within <link + linkend="language.basic-syntax.phpmode">valid PHP start and end + tags</link>. + </simpara> + <para> + This happens each time the <function>include</function> statement + is encountered, so you can use an <function>include</function> + statement within a looping structure to include a number of + different files. + <informalexample> + <programlisting role="php"> +<![CDATA[ +$files = array ('first.inc', 'second.inc', 'third.inc'); +for ($i = 0; $i < count($files); $i++) { + include $files[$i]; +} +]]> + </programlisting> + </informalexample> + </para> + <para> + <function>include</function> differs from + <function>require</function> in that the include statement is + re-evaluated each time it is encountered (and only when it is + being executed), whereas the <function>require</function> + statement is replaced by the required file when it is first + encountered, whether the contents of the file will be evaluated or + not (for example, if it is inside an <link + linkend="control-structures.if">if</link> statement whose + condition evaluated to &false;). + </para> + <para> + Because <function>include</function> is a special language + construct, you must enclose it within a statement block if it is + inside a conditional block. + <informalexample> + <programlisting role="php"> +<![CDATA[ +/* This is WRONG and will not work as desired. */ + +if ($condition) + include($file); +else + include($other); + +/* This is CORRECT. */ + +if ($condition) { + include($file); +} else { + include($other); +} +]]> + </programlisting> + </informalexample> + </para> + <simpara> + In both PHP 3 and PHP 4, it is possible to execute a + <literal>return</literal> statement inside an + <function>include</function>ed file, in order to terminate + processing in that file and return to the script which called + it. Some differences in the way this works exist, however. The + first is that in PHP 3, the <literal>return</literal> may not + appear inside a block unless it's a function block, in which case + the <literal>return</literal> applies to that function and not the + whole file. In PHP 4, however, this restriction does not + exist. Also, PHP 4 allows you to return values from + <function>include</function>ed files. You can take the value of + the <function>include</function> call as you would a normal + function. This generates a parse error in PHP 3. + </simpara> + <example> + <title><function>include</function> in PHP 3 and PHP 4</title> + <para> + Assume the existence of the following file (named + <filename>test.inc</filename>) in the same directory as the main + file: + <programlisting role="php"> +<![CDATA[ +<?php +echo "Before the return <br>\n"; +if (1) { + return 27; +} +echo "After the return <br>\n"; +?> +]]> + </programlisting> + </para> + <para> + Assume that the main file (<filename>main.html</filename>) + contains the following: + <programlisting role="php"> +<![CDATA[ +<?php +$retval = include ('test.inc'); +echo "File returned: '$retval'<br>\n"; +?> +]]> + </programlisting> + </para> + <para> + When <filename>main.html</filename> is called in PHP 3, it will + generate a parse error on line 2; you can't take the value of an + <function>include</function> in PHP 3. In PHP 4, however, the + result will be: + <screen> +Before the return +File returned: '27' + </screen> + </para> + <para> + Now, assume that <filename>main.html</filename> has been altered + to contain the following: + <programlisting role="php"> +<![CDATA[ +<?php +include ('test.inc'); +echo "Back in main.html<br>\n"; +?> +]]> + </programlisting> + </para> + <para> + In PHP 4, the output will be: + <screen> +Before the return +Back in main.html + </screen> + However, PHP 3 will give the following output: + <screen> +Before the return +27Back in main.html + +Parse error: parse error in /home/torben/public_html/phptest/main.html on line 5 + </screen> + </para> + <para> + The above parse error is a result of the fact that the + <literal>return</literal> statement is enclosed in a non-function + block within <filename>test.inc</filename>. When the return is + moved outside of the block, the output is: + <screen> +Before the return +27Back in main.html + </screen> + </para> + <para> + The spurious '27' is due to the fact that PHP 3 does not support + <literal>return</literal>ing values from files like that. + </para> + </example> + <simpara> + When a file is <function>include</function>ed, the code it + contains inherits the variable scope of the line on which the + <function>include</function> occurs. Any variables available at + that line in the calling file will be available within the called + file. If the <function>include</function> occurs inside a + function within the calling file, then all of the code contained + in the called file will behave as though it had been defined + inside that function. + </simpara> + <para> + If the <function>include</function>ed file is called via HTTP + using the fopen wrappers, and if the target server interprets the + target file as PHP code, variables may be passed to the + <function>include</function>ed file using an URL request string as + used with HTTP GET. This is not strictly speaking the same thing + as <function>include</function>ing the file and having it inherit + the parent file's variable scope; the script is actually being run + on the remote server and the result is then being included into + the local script. + <informalexample> + <programlisting role="php"> +<![CDATA[ +/* This example assumes that someserver is configured to parse .php + * files and not .txt files. Also, 'works' here means that the variables + * $varone and $vartwo are available within the include()ed file. */ + +/* Won't work; file.txt wasn't handled by someserver. */ +include ("http://someserver/file.txt?varone=1vartwo=2"); + +/* Won't work; looks for a file named 'file.php?varone=1&vartwo=2' + * on the local filesystem. */ +include ("file.php?varone=1&vartwo=2"); + +/* Works. */ +include ("http://someserver/file.php?varone=1&vartwo=2"); + +$varone = 1; +$vartwo = 2; +include ("file.txt"); /* Works. */ +include ("file.php"); /* Works. */ +]]> + </programlisting> + </informalexample> + </para> + <simpara> + See also <function>require</function>, <function>require_once</function>, + <function>include_once</function>, <function>readfile</function>, + and <function>virtual</function>. + </simpara> + </sect1> + + <sect1 id="function.require-once"> + <title><function>require_once</function></title> + <para> + The <function>require_once</function> statement replaces + itself with the specified file, much like the C preprocessor's + <literal>#include</literal> works, and in that respect is + similar to the <function>require</function> statement. The main + difference is that in an inclusion chain, the use of + <function>require_once</function> will assure that the code is + added to your script only once, and avoid clashes with variable + values or function names that can happen. + </para> + <para> + For example, if you create the following 2 include files + <literal>utils.inc</literal> and <literal>foolib.inc</literal> + <example> + <title>utils.inc</title> + <programlisting role="php"> +<![CDATA[ +<?php +define("PHPVERSION", floor(phpversion())); +echo "GLOBALS ARE NICE\n"; +function goodTea() +{ + return "Oolong tea tastes good!"; +} +?> +]]> + </programlisting> + </example> + <example> + <title>foolib.inc</title> + <programlisting role="php"> +<![CDATA[ +<?php +require ("utils.inc"); +function showVar($var) +{ + if (PHPVERSION == 4) { + print_r($var); + } else { + var_dump($var); + } +} + +// bunch of other functions ... +?> +]]> + </programlisting> + </example> + And then you write a script <literal>cause_error_require.php</literal> + <example> + <title>cause_error_require.php</title> + <programlisting role="php"> +<![CDATA[ +<?php +require("foolib.inc"); +/* the following will generate an error */ +require("utils.inc"); +$foo = array("1",array("complex","quaternion")); +echo "this is requiring utils.inc again which is also\n"; +echo "required in foolib.inc\n"; +echo "Running goodTea: ".goodTea()."\n"; +echo "Printing foo: \n"; +showVar($foo); +?> +]]> + </programlisting> + </example> + When you try running the latter one, the resulting ouptut will be (using + PHP 4.01pl2): + <informalexample> + <screen> +<![CDATA[ +GLOBALS ARE NICE +GLOBALS ARE NICE + +Fatal error: Cannot redeclare goodTea() in utils.inc on line 5 +]]> + </screen> + </informalexample> + By modifying <literal>foolib.inc</literal> and + <literal>cause_errror_require.php</literal> + to use <function>require_once</function> + instead of <function>require</function> and renaming the + last one to <literal>avoid_error_require_once.php</literal>, we have: + <example> + <title>foolib.inc (fixed)</title> + <programlisting role="php"> +<![CDATA[ +... +require_once("utils.inc"); +function showVar($var) +{ +... +]]> + </programlisting> + </example> + <example> + <title>avoid_error_require_once.php</title> + <programlisting role="php"> +<![CDATA[ +... +require_once("foolib.inc"); +require_once("utils.inc"); +$foo = array("1",array("complex","quaternion")); +... +]]> + </programlisting> + </example> + And when running the latter, the output will be (using PHP 4.0.1pl2): + <informalexample> + <screen> +<![CDATA[ +GLOBALS ARE NICE +this is requiring globals.inc again which is also +required in foolib.inc +Running goodTea: Oolong tea tastes good! +Printing foo: +Array +( + [0] => 1 + [1] => Array + ( + [0] => complex + [1] => quaternion + ) + +) +]]> + </screen> + </informalexample> + </para> + <para> + Also note that, analogous to the behavior of the + <literal>#include</literal> of the C preprocessor, this statement + acts at "compile time", e.g. when the script is parsed and before it + is executed, and should not be used for parts of the script that need + to be inserted dynamically during its execution. You should use + <function>include_once</function> or <function>include</function> + for that purpose. + </para> + <para> + For more examples on using <function>require_once</function> and + <function>include_once</function>, look at the PEAR code included in + the latest PHP source code distributions. + </para> + <para> + See also: <function>require</function>, + <function>include</function>, <function>include_once</function>, + <function>get_required_files</function>, + <function>get_included_files</function>, <function>readfile</function>, + and <function>virtual</function>. + </para> + </sect1> + + <sect1 id="function.include-once"> + <title><function>include_once</function></title> + <para> + The <function>include_once</function> statement includes and evaluates + the specified file during the execution of the script. + This is a behavior similar to the <function>include</function> statement, + with the important difference that if the code from a file has already + been included, it will not be included again. + </para> + <para> + As mentioned in the <function>require_once</function> description, the + <function>include_once</function> should be used in the cases in which + the same file might be included and evaluated more than once during a + particular execution of a script, and you want to be sure that it is + included exactly once to avoid problems with function redefinitions, + variable value reassignments, etc. + </para> + <para> + For more examples on using <function>require_once</function> and + <function>include_once</function>, look at the PEAR code included in + the latest PHP source code distributions. + </para> + <para> + <function>include_once</function> was added in PHP 4.0.1pl2 + </para> + <para> + See also: <function>require</function>, + <function>include</function>, <function>require_once</function>, + <function>get_required_files</function>, + <function>get_included_files</function>, <function>readfile</function>, + and <function>virtual</function>. + </para> + </sect1> + + </chapter> + +<!-- Keep this comment at the end of the file +Local variables: +mode: sgml +sgml-omittag:t +sgml-shorttag:t +sgml-minimize-attributes:nil +sgml-always-quote-attributes:t +sgml-indent-step:1 +sgml-indent-data:t +sgml-parent-document:nil +sgml-default-dtd-file:"../../manual.ced" +sgml-exposed-tags:nil +sgml-local-catalogs:nil +sgml-local-ecat-files:nil +End: +vim600: syn=xml fen fdm=syntax fdl=2 si +vim: et tw=78 syn=sgml +vi: ts=1 sw=1 +-->