ae Sat Jun 1 10:10:03 2002 EDT Modified files: /phpdoc-pt_BR/language control-structures.xml Log: review
Index: phpdoc-pt_BR/language/control-structures.xml diff -u phpdoc-pt_BR/language/control-structures.xml:1.6 phpdoc-pt_BR/language/control-structures.xml:1.7 --- phpdoc-pt_BR/language/control-structures.xml:1.6 Wed Dec 12 15:56:35 2001 +++ phpdoc-pt_BR/language/control-structures.xml Sat Jun 1 10:10:02 2002 @@ -1,15 +1,17 @@ <?xml version="1.0" encoding="iso-8859-1"?> +<!-- EN-Revision: 1.58 Maintainer: ae Status: ready --> <chapter id="control-structures"> <title>Estruturas de Controle</title> <simpara> - Qualquer script PHP é construído por uma série de comandos. Um comando - pode ser uma atribuição, uma chamada de função, um 'loop', um comando - condicional, ou mesmo um comando que não faz nada( um comando vazio). - Comandos geralmente terminam com um ponto-e-vírgula. Além disso, os - comandos podem ser agrupados em um grupo de comandos através do encapsulamento - de um grupo de comandos com colchetes. Um grupo de comandos é um comando - também. Os vários tipos de comandos são descritos neste capítulo. + Qualquer script PHP é construído por uma série de instruções. Uma instrução + pode ser uma atribuição, uma chamada de função, um 'loop', uma instrução + condicional, ou mesmo uma instrução que não faz nada(um comando vazio). + Instruções geralmente terminam com um ponto e vírgula. Além disso, as + instruções podem ser agrupados em um grupo de comandos através do encapsulamento + de um grupo de comandos com chaves. Um grupo de comandos é uma instrução + também. Os vários tipos de instruções são + descritos neste capítulo. </simpara> <sect1 id="control-structures.if"> @@ -17,179 +19,204 @@ <para> A construção <literal>if</literal> é uma das mais importantes implementações de muitas linguagens, incluindo o PHP. Ela permite a execução condicional de fragmentos - de código. O PHP implementa uma estrutura <literal>if</literal> + de código. O PHP implementa uma estrutura <literal>if</literal> que é similar àquela do C: <informalexample> <programlisting> -if (expr) - statement +<![CDATA[ +if (expressao) + instrucoes +]]> </programlisting> </informalexample> </para> <simpara> - Como descrito na seção sobre expressões, expr é avaliada por seu valor verdadeiro. - Se <replaceable>expr</replaceable> for avaliada como - &true;, o PHP executará o comando, e se for avaliada como - &false; - o PHP o ignorará o comando. + Como descrita na <link linkend="language.expressions">seção sobre + expressões </link>, <replaceable>expressao</replaceable> é avaliado por seu + contexto Booleano. Se <replaceable>expressao</replaceable> for avaliado como +&true;, + o PHP executará <replaceable>instrucoes</replaceable>, e se for avaliado + como &false;, ele será ignorado. Maiores informações sobre a avaliação + para &false; podem ser encontradas na seção <link + linkend="language.types.boolean.casting">Convertendo para Booleanos</link> + . </simpara> <para> - Os exemplos a seguir mostrariam <computeroutput>a é maior que + Os exemplos a seguir mostrariam que <computeroutput>a é maior que b</computeroutput> se <replaceable>$a</replaceable> for maior que <replaceable>$b</replaceable>: <informalexample> <programlisting role="php"> +<![CDATA[ if ($a > $b) print "a é maior que b"; +]]> </programlisting> </informalexample> </para> <para> - Frequentemente você vai querer ter mais que um comando a ser executado condicionalmente. - É claro, não há necessidade de englobar cada comando com uma cláusula - <literal>if</literal>. Em vez disso, você pode agrupar vários comandos em um grupo de - comandos. Por exemplo, este código mostraria <computeroutput>a é maior que b</computeroutput> + Freqüentemente você vai querer ter mais que uma instrução seja executado + condicionalmente. E é claro, não há necessidade de englobar cada instrução + com uma cláusula <literal>if</literal>. Em vez disso, você pode colocar + várias instruções em um agrupamento de comandos. Por exemplo, este código + mostraria <computeroutput>a é maior que b</computeroutput> se <replaceable>$a</replaceable> for maior que - <replaceable>$b</replaceable>, e então atribuiria o valor de + <replaceable>$b</replaceable>, e então atribuiria o valor de <replaceable>$a</replaceable> para <replaceable>$b</replaceable>: <informalexample> <programlisting role="php"> +<![CDATA[ if ($a > $b) { print "a é maior que b"; $b = $a; } +]]> </programlisting> </informalexample> </para> <simpara> - Comandos 'if' podem ser aninhados indefinidamente dentro de outros comandos + Comandos <literal>if</literal> podem ser aninhados indefinidamente dentro de +outros comandos <literal>if</literal>, o que faz com que você complete a flexibilidade para a - execução condicional de várias partes do seu programa. + execução condicional de várias partes do seu + programa. </simpara> </sect1> - + <sect1 id="control-structures.else"> <title><literal>else</literal></title> <para> - Frequentemente você vai querer executar um comando se uma certa condição for encontrada, e - e um comando diferente se a condição não for encontrada. Isto é o que - o <literal>else</literal> faz. <literal>else</literal> estende um comando - <literal>if</literal> para executar um comando caso a expressão no comando - <literal>if</literal> seja avaliada como &false;. Por exemplo, o código a - seguir mostraria <computeroutput>a é maior que b</computeroutput> se <replaceable>$a</replaceable> - for maior que <replaceable>$b</replaceable>, e <computeroutput>a NÃO é maior que + Freqüentemente você vai querer executar uma instrução se uma certa condição for + encontrada, e uma instrução diferente se a condição não for encontrada. Isto + é o que o <literal>else</literal> faz. <literal>else</literal> + estende um comando <literal>if</literal> para executar uma instrução + caso a expressão no comando <literal>if</literal> + seja avaliada como &false;. Por exemplo, o código a + seguir mostraria <computeroutput>a é maior que + b</computeroutput> se <replaceable>$a</replaceable> for maior que + <replaceable>$b</replaceable>, e <computeroutput>a NÃO é maior que b</computeroutput> caso contrário: <informalexample> <programlisting role="php"> +<![CDATA[ if ($a > $b) { print "a é maior que b"; } else { print "a NÃO é maior que b"; } +]]> </programlisting> </informalexample> O comando <literal>else</literal> só é executado se a expressão <literal>if</literal> for avaliada como - &false;, e se houver qualquer expressão - <literal>elseif</literal> - somente se eles forem avaliadas como + &false;, e se havendo qualquer expressão + <literal>elseif</literal>, somente se todas elas forem avaliadas como &false; também (veja <link linkend="control-structures.elseif">elseif</link>). </para> </sect1> - + <sect1 id="control-structures.elseif"> <title><literal>elseif</literal></title> <para> <literal>elseif</literal>, como seu nome sugere, é uma combinação de <literal>if</literal> e <literal>else</literal>. Da mesma forma que o <literal>else</literal>, ele estende um comando <literal>if</literal> - para executar um comando diferente no caso de a expressão + para executar uma instrução diferente no caso de a expressão <literal>if</literal> original ser avaliada como - &false;. Porém, ao contrário de - <literal>else</literal>, ele executará aquela expressão alternativa - somente se a expressão condicional do <literal>elseif</literal> for + &false;. Porém, ao contrário de + <literal>else</literal>, ele executará aquela expressão alternativa + somente se a expressão condicional do <literal>elseif</literal> for avaliada como &true;. Por exemplo, o código a seguir - mostraria <computeroutput>a é maior que + mostraria <computeroutput>a é maior que b</computeroutput>, <computeroutput>a é igual a b</computeroutput> ou <computeroutput>a é menor que b</computeroutput>: <informalexample> <programlisting role="php"> +<![CDATA[ if ($a > $b) { print "a é maior que b"; } elseif ($a == $b) { print "a é igual a b"; } else { - print "a é menor que b"; + print "a é menor que b b"; } +]]> </programlisting> </informalexample> </para> <simpara> - Podem haver vários <literal>elseif</literal>s dentro do mesmo comando + Podem haver vários <literal>elseif</literal>s dentro da mesma instrução <literal>if</literal>. A primeira expressão <literal>elseif</literal> (se houver) que for avaliada como - &true; será executada. Em PHP, você também pode escrever - 'else if' (em duas palavras) e o comportamento será indêntico a um - 'elseif' (em uma só palavra). O significado sintático é ligeiramente diferente - (se você está familiarizado com C, isto tem o mesmo comportamento), - mas o resultado é que ambos resultariam exatamente no mesmo comportamento. + &true; será executada. No PHP, você também pode + escrever 'else if' (em duas palavras) e o comportamento será idêntico a um + 'elseif' (em uma só palavra). O significado sintático + é ligeiramente diferente (se você está familiarizado com C, eles tem o mesmo + comportamento), mas no final de contas ambos teriam exatamente + o mesmo comportamento. </simpara> <simpara> O comando <literal>elseif</literal> só é executado se a expressão <literal>if</literal> precedente e quaisquer expressões - <literal>elseif</literal> precedentes forem avaliadas como + <literal>elseif</literal> anteriores forem avaliadas como &false;, e a expressão - <literal>elseif</literal> corrente for avaliada como + <literal>elseif</literal> atual for avaliada como &true;. </simpara> </sect1> - + <sect1 id="control-structures.alternative-syntax"> <title>Sintaxe alternativa para estruturas de controle</title> <para> O PHP oferece uma sintaxe alternativa para algumas das suas estruturas - de controle; nominalmente, <literal>if</literal>, - <literal>while</literal>, <literal>for</literal>, e - <literal>switch</literal>. Em cada caso, a forma básica da sintaxe alternativa é mudar - o sinal de abertura para dois-pontos (:) e o sinal de fechamento para <literal>endif;</literal>, - <literal>endwhile;</literal>, <literal>endfor;</literal>, ou + de controle: <literal>if</literal>, + <literal>while</literal>, <literal>for</literal>, + <literal>foreach</literal> e <literal>switch</literal>. + Em cada caso, a forma básica da sintaxe alternativa é mudar + o sinal de abertura para dois-pontos (:) e o sinal de fechamento para + <literal>endif;</literal>, <literal>endwhile;</literal>, + <literal>endfor;</literal>, <literal>endforeach;</literal> ou <literal>endswitch;</literal>, respectivamente. <informalexample> <programlisting role="php"> - <?php if ($a == 5): ?> - A é igual a 5 - <?php endif; ?> +<![CDATA[ +<?php if ($a == 5): ?> +A é igual a 5 +<?php endif; ?> +]]> </programlisting> </informalexample> </para> <simpara> - No exemplo acima, o bloco HTML "A = 5" está aninhado dentro de um comando + No exemplo acima, o bloco HTML "A é igual a 5" está aninhado dentro de uma +instrução <literal>if</literal> escrito na sintaxe alternativa. - O bloco HTML seria mostrado somente se $a é igual a 5. + O bloco HTML será mostrado somente se $a é igual a 5. </simpara> <para> A sintaxe alternativa se aplica a <literal>else</literal> e - <literal>elseif</literal> também. A seguir vem uma estrutura + <literal>elseif</literal> também. A seguir temos uma estrutura <literal>if</literal> com <literal>elseif</literal> e <literal>else</literal> no formato alternativo: <informalexample> <programlisting role="php"> +<![CDATA[ if ($a == 5): - print "a é igual a 5"; + print "a igual a 5"; print "..."; elseif ($a == 6): - print "a é igual a 6"; + print "a igual a 6"; print "!!!"; else: - print "a não é 5 nem 6"; + print "a não é nem 5 nem 6"; endif; +]]> </programlisting> </informalexample> </para> <para> - Veja também <link linkend="control-structures.while">while</link>, - <link linkend="control-structures.for">for</link>, e <link + Veja também: <link linkend="control-structures.while">while</link>, + <link linkend="control-structures.for">for</link> e <link linkend="control-structures.if">if</link> para mais exemplos. </para> </sect1> @@ -202,142 +229,160 @@ <literal>while</literal> é: <informalexample> <programlisting> -while (expr) statement +<![CDATA[ +while (expressao) instrucoes +]]> </programlisting> </informalexample> </para> <simpara> - O significado de um comando <literal>while</literal> é simples. Ele pede que o PHP - execute os comandos aninhados repetidamente, enquanto a expressão - <literal>while</literal> é avaliada como - &true;. O valor da expressão é verificada cada vez que se passa - no começo do 'loop', desta forma mesmo que este valor mude durante a execução do(s) - comando(s) aninhado(s), a execução não parará até que o fim da iteração (cada vez que o - PHP roda os comandos dentro do 'loop' é uma iteração). Às vezes, se a expressão - <literal>while</literal> é avaliada como &false; logo no início, - o(s) comando(s) aninhado(s) não será(ão) rodado(s) nem uma vez sequer. - </simpara> - <para> - Como no comando <literal>if</literal>, você pode agrupar múltiplos comandos dentro - do mesmo 'loop' <literal>while</literal> englobando um grupo de comandos com - colchetes, ou usando a sintaxe alternativa: + O significado de um comando <literal>while</literal> é simples. Ele + pede que o PHP execute os comandos aninhados repetidamente, enquanto + a expressão do <literal>while</literal> é avaliada como + &true;. O valor da expressão é verificada + cada vez que se passa no começo do 'loop', desta forma, mesmo que este valor + mude durante a execução do(s) comando(s) aninhado(s), a execução + não parará até que o fim da iteração (cada vez que o PHP executa + os comandos dentro do 'loop' é uma iteração). Às vezes, se a + expressão <literal>while</literal> é avaliada como + &false; logo no início, o(s) comando(s) + aninhado(s) não será(ão) rodado(s) nem uma vez sequer. + </simpara> + <para> + Como no comando <literal>if</literal>, você pode agrupar + múltiplos comandos dentro do mesmo laço <literal>while</literal> + englobando um grupo de instruções com chaves, ou + usando a sintaxe alternativa: <informalexample> <programlisting> -while (expr): statement ... endwhile; +<![CDATA[ +while (expressao): instrucoes ... endwhile; +]]> </programlisting> </informalexample> </para> <para> - Os exemplos a seguir são idênticos, e ambos imprimem números de 1 to 10: + Os exemplos a seguir são idênticos, e ambos imprimem números de + 1 to 10: <informalexample> - <programlisting> + <programlisting role="php"> +<![CDATA[ /* exemplo 1 */ $i = 1; -while ($i <= 10) { - print $i++; /* o valor impresso será - $i antes do incremento - (pós-incremento) */ +while ($i <= 10) { + print $i++; /* o valor impresso será + $i depois do acréscimo + (post-increment) */ } - + /* exemplo 2 */ - + $i = 1; -while ($i <= 10): +while ($i <= 10): print $i; $i++; endwhile; +]]> </programlisting> </informalexample> </para> </sect1> - + <sect1 id="control-structures.do.while"> <title><literal>do..while</literal></title> <simpara> - Loops <literal>do..while</literal> são bem similares aos 'loops' - <literal>while</literal>, exceto pelo fato de que expressões-verdade - são verificadas no fim de cada iteração em vez de no começo. - A diferença principal dos 'loops' <literal>while</literal> regulares é que - a primeira iteração de um 'loop' <literal>do..while</literal> é garantidamente - rodada (a expressão-verdade só é verificada no fim da iteração), enquanto que - ele pode não rodar necessariamente em um 'loop' - <literal>while</literal> regular (a expressão-verdade é verificada no começo de - cada iteração, se ela é avaliada como - &false; logo no começo, a execução do 'loop' terminaria - imediatamente). + Loops <literal>do..while</literal> são bem similares aos loops + <literal>while</literal>, exceto pelo fato de que a condição + é verificada no fim de cada iteração em vez de no começo. + A diferença principal dos loops <literal>while</literal> regulares é que + a primeira iteração de um loop <literal>do..while</literal> é garantidamente + executada (a condição só é verificada no fim + da iteração) enquanto que ele pode não rodar necessariamente em um loop + <literal>while</literal> normal (a condição é + verificada no começo de cada iteração, se ela é avaliada como + &false; logo no começo, a execução do loop + terminaria imediatamente). </simpara> <para> - Há apenas uma sintaxe para 'loops' <literal>do..while</literal>: - + Há apenas uma sintaxe para loops <literal>do..while</literal>: + <informalexample> <programlisting role="php"> +<![CDATA[ $i = 0; do { print $i; } while ($i>0); +]]> </programlisting> </informalexample> </para> <simpara> - O 'loop' acima rodaria exatamente uma vez, desde que depois da primeira - iteração, quando a expressão-verdade é verificada, ela é avaliada como - &false; ($i não é maior que zero 0) e a execução do 'loop' + O loop acima rodaria exatamente uma vez, desde que depois da primeira + iteração, quando a condição é verificada, ela é avaliada como + &false; ($i não é maior que zero 0) e a execução do loop termina. </simpara> <para> Usuários avançados de C podem estar familiarizados com o uso diferenciado do - 'loop' <literal>do..while</literal>, para permitir o fim da execução no + loop <literal>do..while</literal>, para permitir o fim da execução no meio dos blocos de código, englobando-os com - <literal>do..while</literal>(0), e usando o comando <link + <literal>do..while</literal>(0), e usando a instrução <link linkend="control-structures.break"><literal>break</literal></link> - statement. O fragmento de código a seguir demonstra isso: + . O fragmento de código a seguir demonstra isso: <informalexample> <programlisting role="php"> +<![CDATA[ do { - if ($i < 5) { + if ($i < 5) { print "i não é grande o suficiente"; break; } $i *= $factor; - if ($i < $minimum_limit) { + if ($i < $minimum_limit) { break; } - print "i está correto"; + print "i está Ok"; ...process i... } while(0); +]]> </programlisting> </informalexample> </para> <simpara> Não se preocupe se você não entendeu isto da forma certa ou de jeito nenhum. - Você pode codificar scripts e mesmo poderosos scripts sem usar essa - `opção'. + Você pode codificar scripts simples ou mesmo poderosos sem usar essa + 'opção'. </simpara> </sect1> - + <sect1 id="control-structures.for"> <title><literal>for</literal></title> <para> - Loops <literal>for</literal> são os 'loops' mais complexos em PHP. - Eles se comportam como os seus compatíveis em C. A sintaxe de um 'loop' + Loops <literal>for</literal> são os laços mais complexos em PHP. + Eles se comportam como os seus compatíveis em C. A sintaxe de um loop <literal>for</literal> é: <informalexample> <programlisting> -for (expr1; expr2; expr3) statement +<![CDATA[ +for (expr1; expr2; expr3) instrucoes +]]> </programlisting> </informalexample> </para> <simpara> A primeira expressão (<replaceable>expr1</replaceable>) é - avaliada (executada) uma vez incondicionalmente no começo do 'loop'. + avaliada (executada) uma vez incondicionalmente no começo do + loop. </simpara> <simpara> - No começo de cada iteração, <replaceable>expr2</replaceable> é avaliada. - Se ela é avaliada como &true;, o 'loop' continua e o(s) - comando(s) aninhado(s) é(são) executado(s). Se é avaliada como + No começo de cada iteração, + <replaceable>expr2</replaceable> é avaliada. Se ela é avaliada como + &true;, o loop continua e o(s) comando(s) + aninhado(s) é(são) executado(s). Se é avaliada como &false;, a execução do 'loop' termina. </simpara> <simpara> @@ -346,144 +391,170 @@ </simpara> <simpara> Cada uma das expressões pode ser vazia. - <replaceable>expr2</replaceable> vazia significa que o 'loop' pode rodar + <replaceable>expr2</replaceable> vazia significa que o loop pode rodar indefinidamente (PHP considera-a implicitamente como - &true;, como em C). Isto pode não ser tão inútil quanto - você pode pensar, pois frequentemente você pode querer terminar o 'loop' - usando um comando <link + &true;, como em C). Isto pode não ser tão inútil quanto + você pode pensar, pois freqüentemente você pode querer terminar o 'loop' + usando uma instrução <link linkend="control-structures.break"><literal>break</literal></link> condicional em vez de usar a expressão-verdade do <literal>for</literal>. + </simpara> <para> - Considere os seguintes exemplos. Todos eles mostram números de 1 a 10: + Considere os seguintes exemplos. Todos eles mostram números de + 1 a 10: <informalexample> <programlisting role="php"> +<![CDATA[ /* exemplo 1 */ - -for ($i = 1; $i <= 10; $i++) { + +for ($i = 1; $i <= 10; $i++) { print $i; } - + /* exemplo 2 */ - + for ($i = 1;;$i++) { - if ($i > 10) { + if ($i > 10) { break; } print $i; } - + /* exemplo 3 */ - + $i = 1; for (;;) { - if ($i > 10) { + if ($i > 10) { break; } print $i; $i++; } - + /* exemplo 4 */ - -for ($i = 1; $i <= 10; print $i, $i++) ; + +for ($i = 1; $i <= 10; print $i, $i++); +]]> </programlisting> </informalexample> </para> <simpara> - Obviamente, o primeiro exemplo parece ser o mais bonito (ou talvez o quarto), mas - você pode perceber que a possível utilização de expressões vazias em 'loops' - <literal>for</literal> se torna prático em muitas ocasiões. + Obviamente, o primeiro exemplo parece ser o mais bonito (ou + talvez o quarto), mas você pode perceber que a possível utilização de expressões + vazias em laços <literal>for</literal> se torna prático em algumas + ocasiões. </simpara> <para> - O PHP também suporta a "sintaxe de dois-pontos" alternativa para 'loops' - <literal>for</literal>. + O PHP também suporta a "sintaxe de dois-pontos" alternativa para + laços <literal>for</literal>: <informalexample> <programlisting> -for (expr1; expr2; expr3): statement; ...; endfor; +<![CDATA[ +for (expr1; expr2; expr3): instrucoes; ...; endfor; +]]> </programlisting> </informalexample> </para> <para> - Outras linguagens têm um comando <literal>foreach</literal> para varrer uma - matriz ou tabela de hashing. O PHP3 não tem uma construção deste tipo; O PHP4 tem - (veja <link linkend="control-structures.foreach">foreach</link>). Em PHP3, + Outras linguagens têm uma instrução <literal>foreach</literal> + para varrer uma matriz ou tabela de hashing. O PHP 3 não tem uma construção deste +tipo; O PHP 4 possui + (veja <link + linkend="control-structures.foreach">foreach</link>). No PHP 3, você pode combinar <link linkend="control-structures.while">while</link> com as funções <function>list</function> e <function>each</function> para - obter o mesmo efeito. Veja a documentação para estas funções para ter um - exemplo. + obter o mesmo efeito. Veja a documentação para estas funções para + exemplos. </para> </sect1> + <sect1 id="control-structures.foreach"> <title><literal>foreach</literal></title> <para> - O PHP4 (não o PHP3) inclui uma construção <literal>foreach</literal>, - muito parecido com o perl e outras linguagens. Isto simplesmente oferece uma - maneira fácil de iterar sobre matrizes. Há duas sintaxes; a segunda é uma - extensão menor, mas útil, da primeira: + O PHP4 (mas não o PHP3) inclui uma construção <literal>foreach</literal>, + muito parecido com o PERL e outras linguagens. Isto simplesmente oferece uma + maneira fácil de iterar sobre matrizes. Há duas sintaxes; a segunda é uma + abreviatura, mas útil, da primeira: <informalexample> <programlisting> -foreach(array_expression as $value) statement -foreach(array_expression as $key => $value) statement +<![CDATA[ +foreach(expressao_array as $valor) instrucoes +foreach(expressao_array as $chave => $valor) instrucoes +]]> </programlisting> </informalexample> </para> <simpara> A primeira forma varre uma dada matriz dada por - <literal>array_expression</literal>. Em cada 'loop', o valor do elemento - corrente é atribuído a <literal>$value</literal> e o ponteiro interno da - matriz é avançado em uma posição (assim, no próximo 'loop' você estará + <literal>expressao_array</literal>. Em cada 'loop', o valor do elemento + corrente é atribuído a <literal>$valor</literal> e o ponteiro interno da + matriz é avançado em uma posição (assim, no próxima iteração você estará olhando para o próximo elemento). </simpara> <simpara> A segunda forma faz a mesma coisa, exceto pelo fato de que a chave do elemento - corrente será atribuído à variável <literal>$key</literal> em cada 'loop'. + atual será atribuído à variável + <literal>$chave</literal> em cada iteração. </simpara> <para> <note> <para> - Quando o <literal>foreach</literal> inicia sua primeira execução, o ponteiro - interno da matriz é zerado automaticamente para o primeiro elemento da matriz. + Quando o <literal>foreach</literal> inicia sua primeira execução, o ponteiro + interno da matriz é zerado automaticamente para o primeiro elemento do array. Isto significa que você não precisa chamar - <function>reset</function> antes de um 'loop' <literal>foreach</literal>. - </para> - </note> + <function>reset</function> antes de um loop <literal>foreach</literal> + . + </para> + </note> </para> <para> <note> - <para> - Note também que <literal>foreach</literal> opera sobre uma cópia da matriz - especificada, não na própria matriz, portanto o ponteiro da matriz não é - modificado como na construção 'each'. - </para> + <para> + Note também que <literal>foreach</literal> opera sobre uma cópia + do array especificado, não o próprio array, portanto o ponteiro da array + não é modificado como na instrução <function>each</function>, + que altera o elemento do array selecionado, mas isso não se reflete + o array original. + </para> </note> </para> + <note> + <para> + <literal>foreach</literal> tem a habilidade de + evitar mensagens de erro com '@'. + </para> + </note> <para> - Você pode ter notado que os seguintes itens são funcionalmente idênticos: + Você pode ter notado que os seguintes itens são funcionalmente + idênticos: <informalexample> <programlisting role="php"> +<![CDATA[ reset ($arr); while (list(, $value) = each ($arr)) { - echo "Value: $value<br>\n"; + echo "Valor: $value<br>\n"; } foreach ($arr as $value) { - echo "Value: $value<br>\n"; + echo "Valor: $value<br>\n"; } +]]> </programlisting> </informalexample> - Os seguintes tanbém são funcionalmente idênticos: + Os seguintes também são funcionalmente idênticos: <informalexample> <programlisting role="php"> +<![CDATA[ reset ($arr); while (list($key, $value) = each ($arr)) { - echo "Key: $key; Value: $value<br>\n"; + echo "Chave: $key; Valor: $value<br>\n"; } foreach ($arr as $key => $value) { - echo "Key: $key; Value: $value<br>\n"; + echo "Chave: $key; Valor: $value<br>\n"; } +]]> </programlisting> </informalexample> </para> @@ -491,798 +562,864 @@ Mais alguns exemplos para demonstrar os usos: <informalexample> <programlisting role="php"> -/* exemplo de foreach 1: só valor */ +<![CDATA[ +/* exemplo foreach 1: somente valores */ $a = array (1, 2, 3, 17); foreach ($a as $v) { - print "Valor corrente de \$a: $v.\n"; + print "Valor atual de \$a: $v.\n"; } -/* exemplo de foreach 2: valor (com a chave impressa para ilustração) */ +/* exemplo foreach 2: valores (com as chaves impressas para ilustração) */ $a = array (1, 2, 3, 17); -$i = 0; /* só para propósito de ilustração */ +$i = 0; /* para exemplo somente */ foreach($a as $v) { - print "\$a[$i] => $k.\n"; + print "\$a[$i] => $v.\n"; + $i++; } -/* exemplo de foreach 3: chave e valor */ +/* exemplo foreach 3: chaves e valores */ $a = array ( - "one" => 1, - "two" => 2, - "three" => 3, - "seventeen" => 17 + "um" => 1, + "dois" => 2, + "três" => 3, + "dezessete" => 17 ); foreach($a as $k => $v) { print "\$a[$k] => $v.\n"; } + +/* exemplo foreach 4: arrays multidimensionais */ + +$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"; + } +} + +/* exemplo foreach 5: arrays dinâmicos */ + +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 a execução da estrutura - <literal>for</literal>, <literal>while</literal>, ou - <literal>switch</literal> corrente. + <literal>break</literal> cancela a execução do comando + <literal>for</literal>, <literal>foreach</literal> + <literal>while</literal>, <literal>do..while</literal> ou + <literal>switch</literal> atual. </simpara> - <simpara> - <literal>break</literal> aceita um argumento numérico opcional que diz a ele - quantas estruturas aninhadas englobadas devem ser quebradas. + <literal>break</literal> aceita um argumento numérico opcional + que diz a ele quantas estruturas aninhadas englobadas devem + ser quebradas. </simpara> - <para> <informalexample> <programlisting role="php"> -$arr = array( 'one', 'two', 'three', 'four', 'stop', 'five' ); -while ( list( , $val ) = each( $arr ) ) { - if ( $val == 'stop' ) { - break; /* Você também poderia escrever 'break 1;' aqui. */ - } - echo "$val<br>\n"; +<![CDATA[ +$arr = array ('um', 'dois', 'três', 'quatro', 'PARE', 'cinco'); +while (list (, $val) = each ($arr)) { + if ($val == 'PARE') { + break; /* Você poderia colocar 'break 1;' aqui. */ + } + echo "$val<br>\n"; } -/* Usando o argumento opcional. */ +/* Utilizando o argumento opcional. */ + $i = 0; -while ( ++$i ) { - switch ( $i ) { +while (++$i) { + switch ($i) { case 5: - echo "At 5<br>\n"; - break 1; /* sai somento de 'switch'. */ + echo "No 5<br>\n"; + break 1; /* Sai somente do switch. */ case 10: - echo "At 10; quitting<br>\n"; - break 2; /* sai de 'switch' e de 'while'. */ + echo "No 10; saindo<br>\n"; + break 2; /* Sai do switch e while. */ default: break; } } +]]> </programlisting> </informalexample> </para> </sect1> - + <sect1 id="control-structures.continue"> <title><literal>continue</literal></title> <simpara> - <literal>continue</literal> é usado dentro de estruturas de 'loops' - para saltar o resto da iteração do 'loop' corrente e continuar a execução + <literal>continue</literal> é usado dentro de estruturas de loops + para saltar o resto da iteração do loop atual e continuar a execução no início da próxima iteração. </simpara> <simpara> <literal>continue</literal> aceita um argumento numérico opcional que diz - a ele de quantos níveis de 'loops' englobados ele deveria saltar até o fim. + a ele de quantos níveis de loops aninhados ele deve saltar + até o fim. </simpara> <para> <informalexample> <programlisting role="php"> +<![CDATA[ while (list ($key, $value) = each ($arr)) { - if (!($key % 2)) { // salta membros ímpares - continue; - } - do_something_odd ($value); + if (!($key % 2)) { // pula itens pares + continue; + } + do_something_odd ($value); } $i = 0; -while ($i++ < 5) { - echo "Mais externo<br>\n"; +while ($i++ < 5) { + echo "Fora<br>\n"; while (1) { - echo " Meio<br>\n"; + echo " Meio<br>\n"; while (1) { - echo " Inner<br>\n"; + echo " Dentro<br>\n"; continue 3; } - echo "This never gets output.<br>\n"; + echo "Isto nunca será exibido.<br>\n"; } - echo "Neither does this.<br>\n"; + echo "Nem isso.<br>\n"; } +]]> </programlisting> </informalexample> </para> </sect1> - + <sect1 id="control-structures.switch"> <title><literal>switch</literal></title> <simpara> - The <literal>switch</literal> statement is similar to a series of - IF statements on the same expression. In many occasions, you may - want to compare the same variable (or expression) with many - different values, and execute a different piece of code depending - on which value it equals to. This is exactly what the - <literal>switch</literal> statement is for. - </simpara> - <para> - The following two examples are two different ways to write the - same thing, one using a series of <literal>if</literal> - statements, and the other using the <literal>switch</literal> - statement: + A instrução <literal>switch</literal> é similar a uma série de + instruções IFs seguidas. Em muitas ocasiões, você poderá ter + que comparar a mesma variável (ou expressão) com muitos + valores diferentes, executando códigos diferentes dependendo + com qual valor ele se encaixar. É exatamente para isso que a + instrução <literal>switch</literal> faz. + </simpara> + <para> + Os exemplos seguintes mostram duas maneiras diferentes de escrever a + mesma coisa, uma utilizando uma série de <literal>is</literal>s + e a outra utlizando a instrução <literal>switch</literal>: + <informalexample> <programlisting role="php"> +<![CDATA[ if ($i == 0) { - print "i equals 0"; + print "i igual a 0"; } if ($i == 1) { - print "i equals 1"; + print "i igual a 1"; } if ($i == 2) { - print "i equals 2"; + print "i igual a 2"; } - + switch ($i) { case 0: - print "i equals 0"; + print "i igual a 0"; break; case 1: - print "i equals 1"; + print "i igual a 1"; break; case 2: - print "i equals 2"; + print "i igual a 2"; break; } +]]> </programlisting> </informalexample> </para> <para> - It is important to understand how the <literal>switch</literal> - statement is executed in order to avoid mistakes. The - <literal>switch</literal> statement executes line by line - (actually, statement by statement). In the beginning, no code is - executed. Only when a <literal>case</literal> statement is found - with a value that matches the value of the - <literal>switch</literal> expression does PHP begin to execute the - statements. PHP continues to execute the statements until the end - of the <literal>switch</literal> block, or the first time it sees - a <literal>break</literal> statement. If you don't write a - <literal>break</literal> statement at the end of a case's - statement list, PHP will go on executing the statements of the - following case. For example: + É importante entender como a instrução <literal>switch</literal> + funciona para evitar enganos. A instrução + <literal>switch</literal> executa linha a linha + (atualmente, instrução a instrução). No início, nenhum código é + executado. Somente quando uma instrução <literal>case</literal> é encontrada + com um valor que combina com a expressão do + <literal>switch</literal> faz com que o PHP execute as + instruções a partir daí. O PHP continua executando as instruções até o fim + do bloco <literal>switch</literal> ou na primeira vez que encontrar + uma instrução <literal>break</literal>. Se você não escrever uma + instrução <literal>break</literal> no fim das instruções + <literal>case</literal>, o PHP continuará executando os + <literal>case</literal>s seguintes. Exemplo: <informalexample> <programlisting role="php"> +<![CDATA[ switch ($i) { case 0: - print "i equals 0"; + print "i igual a 0"; case 1: - print "i equals 1"; + print "i igual a 1"; case 2: - print "i equals 2"; + print "i igual a 2"; } +]]> </programlisting> </informalexample> </para> <simpara> - Here, if $i equals to 0, PHP would execute all of the print - statements! If $i equals to 1, PHP would execute the last two - print statements, and only if $i equals to 2, you'd get the - 'expected' behavior and only 'i equals 2' would be displayed. So, - it's important not to forget <literal>break</literal> statements - (even though you may want to avoid supplying them on purpose under - certain circumstances). + Aqui, se $i é igual a zero, o PHP executará todas as instruções + print!. Se $i é igual a 1, o PHP executará os últimas duas + instruções print, e somente se $i for igual a 2, você terá o + comportamento 'esperado' apenas onde 'i igual a 2' será mostrado. Então + é importante não se esquecer das instruções <literal>break</literal> + (e as vezes não colocá-las para esse resultado em + certas circunstâncias). </simpara> <simpara> - In a <literal>switch</literal> statement, the condition is - evaluated only once and the result is compared to each - <literal>case</literal> statement. In an <literal>elseif</literal> - statement, the condition is evaluated again. If your condition is - more complicated than a simple compare and/or is in a tight loop, - a <literal>switch</literal> may be faster. + Em uma instrução <literal>switch</literal>, a condição + somente será avaliada e resultado comparado para cada + instrução <literal>case</literal>. Em uma instrução + <literal>elseif</literal>, a condição é avaliada novamente. Se sua condição é + mais complicada que um simples comparação e/ou e dentro de um loop, + um <literal>switch</literal> é mais rápido. </simpara> <para> - The statement list for a case can also be empty, which simply - passes control into the statement list for the next case. + Um case pode não ter nenhuma instrução dentro, o que simplesmente + passa o controle para o próximo case. <informalexample> <programlisting role="php"> +<![CDATA[ switch ($i) { case 0: case 1: case 2: - print "i is less than 3 but not negative"; + print "i é menor que 3 mas não negativo"; break; case 3: - print "i is 3"; + print "i é 3"; } +]]> </programlisting> </informalexample> </para> <para> - A special case is the default case. This case matches anything - that wasn't matched by the other cases. For example: + Um case especial é o default. Esse case é executado quando + nenhum outro case combina. Ele precisa ser a última + instrução <literal>case</literal>. Por exemplo: <informalexample> <programlisting role="php"> +<![CDATA[ switch ($i) { case 0: - print "i equals 0"; + print "i igual a 0"; break; case 1: - print "i equals 1"; + print "i igual a 1"; break; case 2: - print "i equals 2"; + print "i igual a 2"; break; default: - print "i is not equal to 0, 1 or 2"; + print "i não é igual a 0, 1 ou 2"; } +]]> </programlisting> </informalexample> </para> <para> - The <literal>case</literal> expression may be any expression that - evaluates to a simple type, that is, integer or floating-point - numbers and strings. Arrays or objects cannot be used here unless - they are dereferenced to a simple type. + A expressão avaliada pelo <literal>case</literal> precisa + ser um tipo simples, ou seja, inteiros, números de ponto flutuante + e strings. Arrays ou objetos não podem ser utilizados a não ser + que eles impliquem num tipo simples. </para> <para> - The alternative syntax for control structures is supported with - switches. For more information, see <link - linkend="control-structures.alternative-syntax">Alternative syntax - for control structures</link> . + A sintaxe alternativa para estruturas de controle é suportada para os + switches. Para maiores informações, veja <link + linkend="control-structures.alternative-syntax">Sintaxe alternativa + para estruturas de controle</link>. <informalexample> <programlisting role="php"> +<![CDATA[ switch ($i): case 0: - print "i equals 0"; + print "i igual a 0"; break; case 1: - print "i equals 1"; + print "i igual a 1"; break; case 2: - print "i equals 2"; + print "i igual a 2"; break; default: - print "i is not equal to 0, 1 or 2"; + print "i não é igual a 0, 1 ou 2"; endswitch; +]]> </programlisting> </informalexample> </para> </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> + + <sect1 id="control-structures.declare"> + <title><literal>declare</literal></title> + <para> + O construtor <literal>declare</literal> é utilizado para + configurar diretivas de execução para blocos de código. + A sintaxe do <literal>declare</literal> é similar + a sintaxe de outros construtores de controle. + <informalexample> + <programlisting> +<![CDATA[ +declare (diretiva) instrucao +]]> + </programlisting> + </informalexample> + </para> + <para> + A seção <literal>diretiva</literal> permite o + comportamento do bloco <literal>declare</literal> a + ser configurado. + Atualmente somente uma diretiva é reconhecida: a + diretiva <literal>ticks</literal>. (veja abaixo para maiores + informações em + <link linkend="control-structures.declare.ticks">diretiva + ticks</link>) + </para> + <para> + A parte <literal>instrucao</literal> do + bloco <literal>declare</literal> será executada - como + ela é executada e que efeitos colaterais que podem ocorrem durante a execução + dependem da configuração + <literal>diretiva</literal>. + </para> + <sect2 id="control-structures.declare.ticks"> + <title>Ticks</title> + <para>Um tick é um evento que ocorre para cada + <replaceable>N</replaceable> níveis de instruções executados + pelo interpretador com o bloco <literal>declare</literal>. + O valor para <replaceable>N</replaceable> é especificado + utilizando <literal>ticks=<replaceable>N</replaceable></literal> + nos blocos <literal>declare</literal> das + seções <literal>diretiva</literal>. + </para> + <para> + O(s) evento(s) que ocorre(m) em cada tick são especificados utilizando + <function>register_tick_function</function>. Veja o exemplo + abaixo para maiores detalhes. Note que mais de um evento pode ocorrer + em cada tick. + </para> + <para> + <example> + <title>Histórico de um trecho de código PHP</title> + <programlisting role="php"> +<![CDATA[ +<?php +// Uma função que grava o tempo entre as chamadas +function profile ($dump = FALSE) +{ + static $profile; + + // Retorna os tempos preservados no histórico, então apaga + if ($dump) { + $temp = $profile; + unset ($profile); + return ($temp); + } + + $profile[] = microtime (); +} + +// Ativa o manipulador do tick +register_tick_function("profile"); + +// Inicializa a função antes de declarar o bloco +profile (); + +// Roda um trecho de código, disparando um tick a cada duas instruções +declare (ticks=2) { + for ($x = 1; $x < 50; ++$x) { + echo similar_text (md5($x), md5($x*$x)), "<br />;"; + } +} + +// Mostra os dados guardados no histórico +print_r (profile (TRUE)); +?> +]]> + </programlisting> + </example> + No exemplo acima, o bloco 'declare' + grava os tempos a cada segundo nível dentro das + instruções no bloco enquanto executam. Esta informação pode + ser utilizada para encontrar áreas lentas em segmentos + particulares de código. Este processo pode ser realizado de outras + formas, mas a utilização de ticks é mais conveniente e fácil de + implementar. + </para> <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. + Ticks são idealizados para debug, implementação de multitask + simples, processos de I/O em background e afins. </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>. + Veja também: <function>register_tick_function</function> e + <function>unregister_tick_function</function>. </simpara> + </sect2> + </sect1> + + <sect1 id="function.return"> + <title>return</title> <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> + Se chamada em uma função, a instrução <function>return</function> + termina imediatamente a execução da função atual e retorna + seu argumento como o valor da função. + <function>return</function> também termina a execução de + uma instrução <function>eval</function> ou de um script. + </simpara> + <simpara> + Se chamada no escopo global, a execução do script + atual será terminada. Se o arquivo do script atual foi + incluído com <function>include</function> ou <function>require</function>, + então a execução é devolvida para o arquivo chamador. Especificamente para + arquivos de script incluídos com <function>include</function>, o + valor fornecido para <function>return</function> será devolvido como + o valor da chamada <function>include</function>. Se + <function>return</function> for chamado do arquivo de script + principal, então o programa pára. Se o arquivo de script atual é + o configurado em <link + linkend="ini.auto-prepend-file">auto_prepend_file</link> ou <link + linkend="ini.auto-append-file">auto_append_file</link> + do <link linkend="configuration.file">arquivo + de configuração</link>, então a execução desses scripts é + finalizada. + </simpara> + <simpara>Para maiores informações, veja <link + linkend="functions.returning-values">Retornando Valores</link>. + </simpara> + <note> + <simpara> + Note que <function>return</function> é um construtor + de linguagem e não uma função, e parênteses em volta do + seus argumentos <emphasis>não são</emphasis> necessários -- de fato, é + mais comum não colocá-los que usá-los, sem, entretanto, haver + diferença de um jeito ou de outro. + </simpara> + </note> + </sect1> + + + <sect1 id="function.require"> + <title><function>require</function></title> + <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. + A instrução <function>require</function> inclui a avalia + um arquivo específico. </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. + + Informações detalhadas de como essa inclusão funciona está descrita na + documentação do <function>include</function>. </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"> -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. + <function>require</function> e <function>include</function> + são idênticos em todas as formas exceto pela manipulação de erros. + <function>include</function> produz um + <link linkend="internal.e-warning">Warning</link> enquanto + <function>require</function> produzirá um <link linkend="internal.e-error"> + Fatal Error</link>. Em outras palavras, não hesite em utilizar + <function>require</function> se na falta de um arquivo quiser parar o +processamento + da página. <function>include</function> não se comporta da mesma maneira, e o + script poderá continuar nessa situação. Em todo caso, vale a pena confirmar a +configuração da diretiva + <link linkend="ini.include-path">include_path</link>. </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> + <example> + <title>Exemplos de <function>require</function>s simples</title> <programlisting role="php"> -/* 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. */ +<![CDATA[ +<?php -/* Won't work; file.txt wasn't handled by someserver. */ -require ("http://someserver/file.txt?varone=1&vartwo=2"); +require 'prepend.php'; -/* 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"); +require $somefile; -/* Works. */ -require ("http://someserver/file.php?varone=1&vartwo=2"); +require ('somefile.txt'); -$varone = 1; -$vartwo = 2; -require ("file.txt"); /* Works. */ -require ("file.php"); /* Works. */ +?> +]]> </programlisting> - </informalexample> + </example> </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>. + Vaja a documentação de <function>include</function> para mais exemplos. </simpara> - <simpara> - See also <function>include</function>, <function>require_once</function>, - <function>include_once</function>, <function>readfile</function>, - and <function>virtual</function>. + <note> + <simpara> + Até o PHP 4.0.2, havia o seguinte comportamento: <function>require</function> + mesmo que a linha onde ele está nunca seja executada. + É por isso que instruções condicionais não afetam <function>require</function>. +Entretanto, + se a linha onde ocorre o <function>require</function> não for executada, + nada do código incluído do arquivo também será. Similarmente, estruturas de + loop não afetam o funcionamento do <function>require</function>. Mas + o código incluído pela função será submetida ao loop. A instrução + <function>require</function> apenas ocorre uma vez. + </simpara> + </note> + <simpara> + Veja também: <function>include</function>, <function>require_once</function>, + <function>include_once</function>, <function>eval</function>, + <function>file</function>, <function>readfile</function>, + <function>virtual</function> e <link +linkend="ini.include-path">include_path</link>. </simpara> </sect1> - - <sect1 id="function.include"> + + <sect1 id="function.include"> <title><function>include</function></title> <simpara> - The <function>include</function> statement includes and evaluates - the specified file. + A instrução <function>include</function> inclui e avalia o + arquivo informado. </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. + A documentação a seguir se aplica também a <function>require</function>. + Esses dois construtores são idênticos a exceção de como eles manipulam + erros. <function>include</function> produz um + <link linkend="internal.e-warning">Warning</link> enquanto +<function>require</function> + produzirá um <link linkend="internal.e-error">Fatal Error</link>. + Em outras palavras, utilize <function>require</function> se você deseja + que um arquivo faltando interrompa o processamento da página. +<function>include</function> + não se comporta da mesma maneira, permitindo que o script continue nessas +situações. Em todo caso, + vale a pena confirmar a configuração da diretiva <link +linkend="ini.include-path">include_path</link>. </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>. + Quando um arquivo é incluído, seu código entra no + <link linkend="language.variables.scope">escopo de variável</link> da + linha onde a inclusão ocorre. Qualquer variável disponível da linha onde + a chamada da inclusão ocorre estará disponível para o arquivo incluído, daquele + ponto em diante. </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"> -$files = array ('first.inc', 'second.inc', 'third.inc'); -for ($i = 0; $i < count($files); $i++) { - include $files[$i]; + <example> + <title>Exemplos de <function>include</function>s simples</title> + <programlisting role="php"> +<![CDATA[ +variaveis.php +<?php + +$cor = 'verde'; +$fruta = 'maçã'; + +?> + +teste.php +<?php + +echo "Uma $fruta $cor"; // Uma + +include 'vars.php'; + +echo "Uma $fruta $cor"; // Uma maçã verde + +?> +]]> + </programlisting> + </example> + </para> + <simpara> + Se o include ocorre dentro de uma função do arquivo principal, + então todo o código incluído será executado como + se ele tivesse sido definido dentro daquela função. Da mesma forma, + ele seguirá o escopo de variáveis da função. + </simpara> + <para> + <example> + <title>Incluindo dentro de funções</title> + <programlisting role="php"> +<![CDATA[ +<?php + +function foo() +{ +global $cor; + + include 'variaveis.php'; + + echo "Uma $fruta $cor"; } + +/* variaveis.php está no escopo de foo(), * +.* então $fruta NÃO está disponível fora de * +.* seu escopo. $cor estará porque ela foi * +.* declarada como global */ + +foo(); // Uma maçã verde +echo "A $fruta $cor"; // Uma maçã + +?> +]]> </programlisting> - </informalexample> + </example> + </para> + <simpara> + Quando um arquivo é incluído, o interpretador sai do modo PHP e + entra no modo HTML (no começo do arquivo incluído), e alterna + novamente no seu fim. Por isso, qualquer código dentro do arquivo + incluído que precisa ser executado como código PHP tem de ser delimitado por + <link linkend="language.basic-syntax.phpmode">tags válidas + de abertura e fechamento</link>. + </simpara> + <simpara> + Se "<link linkend="ini.allow-url-fopen">URL fopen wrappers</link>" + estão ativas no PHP (normalmente na configuração default), + você pode especificar um arquivo utilizando uma URL (via HTTP) + em vez de um caminho local. Se o servidor apontado interpreta + o arquivo informado como código PHP, variáveis podem ser passadas ao arquivo + incluído na URL de requisição como num HTTP GET. Isto não + é necessariamente a mesma coisa que incluir o arquivo e + compartilhar o escopo de variável do arquivo principal: o script + será executado no servidor remoto e apenas seu resultado será + incluído no script local. + </simpara> + <para> + <example> + <title><function>include</function> através de HTTP</title> + <programlisting role="php"> +<![CDATA[ +<?php + +/* Este exemplo assume que www.exemplo.com está configurado para interpretar * + * arquivos .php mas não .txt. Além, 'Funciona' aqui significa que as * + * variáveis $foo e $bar estão disponíveis no arquivo incluído */ + +// Não funciona: arquivos txt não são manipulados em www.example.com como PHP +include 'http://www.exemplo.com/arquivo.txt?foo=1&bar=2'; + +// Não funciona: procura por um arquivo chamado 'arquivo.php?foo=1&bar=2' no +// sistemas de arquivo local. +include 'arquivo.php?foo=1&bar=2'; + +// Funciona. +include 'http://www.exemplo.com/arquivo.php?foo=1&bar=2'; + +$foo = 1; +$bar = 2; +include 'arquivo.txt'; // Funciona. +include 'arquivo.php'; // Funciona. + +?> +]]> + </programlisting> + </example> + Vaja também: <link linkend="features.remote-files">Arquivos Remotos</link>, + <function>fopen</function> e <function>file</function> para informações + relacionadas. </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;). + Por serem <function>include</function> e <function>require</function> + dois construtores de linguagem especiais, você precisa delimitá-los como + um bloco de instruções quando utilizados dentro de instruções condicionais. </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> + <example> + <title>include() e instruções condicionais</title> <programlisting role="php"> -/* This is WRONG and will not work as desired. */ - +<![CDATA[ +<?php + +// Isto está errado e não funcionará como desejado if ($condition) - include($file); + include $arquivo; else - include($other); - -/* This is CORRECT. */ - + include $outro; + + +// E este está correto if ($condition) { - include($file); + include $arquivo; } else { - include($other); + include $outro; } + +?> +]]> </programlisting> - </informalexample> + </example> </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"> -<?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"> -<?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"> -<?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. + Também é possível executar uma instrução <function>return</function> + dentro de um arquivo incluído de maneira a finalizar o processamento daquele + arquivo e retornar para o script que o chamou. Também é possível retornar + valores de arquivos incluídos. Você pode pegar o valor de retorno de um include +como + faria com uma função normal. </simpara> + <note> + <simpara> + No PHP 3, o return não pode aparecer dento de um bloco a não ser que ele + seja um bloco de função, e nesse caso <function>return</function> se aplica + apenas para a função e não para todo o arquivo. + </simpara> + </note> <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"> -/* 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. */ + <example> + <title>Instruções <function>include</function> e +<function>return</function></title> + <programlisting role="php"> +<![CDATA[ +return.php +<?php -/* Won't work; file.txt wasn't handled by someserver. */ -include ("http://someserver/file.txt?varone=1&vartwo=2"); +$var = 'PHP'; -/* 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"); +return $var; -/* Works. */ -include ("http://someserver/file.php?varone=1&vartwo=2"); +?> -$varone = 1; -$vartwo = 2; -include ("file.txt"); /* Works. */ -include ("file.php"); /* Works. */ - </programlisting> - </informalexample> +noreturn.php +<?php + +$var = 'PHP'; + +?> + +testreturns.php +<?php + +$foo = include 'return.php'; + +echo $foo; // imprime 'PHP' + +$bar = include 'noreturn.php'; + +echo $bar; // imprime 1 + +?> +]]> + </programlisting> + </example> </para> <simpara> - See also <function>require</function>, <function>require_once</function>, + <literal>$bar</literal> assimila o valor <literal>1</literal> porque a inclusão + foi realizada com sucesso. Verifique a diferença entre os exemplo. O primeiro +utiliza + <function>return</function> dentro do arquivo incluído enquanto que o outro não. + Há outras maneiras de "incluir" arquivos dentro de variáveis, com + <function>fopen</function>, <function>file</function> ou utilizando + <function>include</function> através das + <link linkend="ref.outcontrol">Funções de Controle de Output</link>. + </simpara> + + <simpara> + Veja também: <function>require</function>, <function>require_once</function>, <function>include_once</function>, <function>readfile</function>, - and <function>virtual</function>. + <function>virtual</function> e + <link linkend="ini.include-path">include_path</link>. </simpara> - </sect1> - - <sect1 id="function.require-once"> + +</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"> -<?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"> -<?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"> -<?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> - <programlisting> -GLOBALS ARE NICE -GLOBALS ARE NICE - -Fatal error: Cannot redeclare goodTea() in utils.inc on line 5 - </programlisting> - </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"> -... -require_once("utils.inc"); -function showVar($var) { -... - </programlisting> - </example> - <example> - <title>avoid_error_require_once.php</title> - <programlisting role="php"> -... -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> - <programlisting> -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 - ) - -) - </programlisting> - </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. + A instrução <function>require_once</function> incluí e avalia + o arquivo especificado durante a execução do script. + Seu comportamento é similar ao da instrução <function>require</function>, + a não ser que o arquivo informado já tenha sido + incluído, não refazendo a operação novamente. Veja a documentação de + <function>require</function> para maiores informações sobre como essa instrução + funciona. + </para> + <para> + <function>require_once</function> pode ser utilizado nos casos em + que o mesmo arquivo pode acabar sendo incluído mais de uma vez durante a + execução de um script em particular, quando na verdade ele só pode ser + incluído apenas uma, para evitar problemas com redefinições de funções, + alterações nos valores de variáveis, etc. + </para> + <para> + Para exemplos de utilização de <function>require_once</function> e + <function>include_once</function>, veja o código do + <ulink url="&url.php.pear;">PEAR</ulink> incluído nas + últimas distribuições do código fonte do PHP. </para> + <note> + <para> + <function>require_once</function> foi acrescentado a partir PHP 4.0.1pl2 + </para> + </note> <para> - See also: <function>require</function>, + Veja também: <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>. + <function>get_included_files</function>, <function>readfile</function> + e <function>virtual</function>. </para> </sect1> - - <sect1 id="function.include-once"> + + <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 + A instrução <function>include_once</function> inclui e avalia + o arquivo especificado durante a execução de um script. + Seu comportamento é similar a instrução <function>include</function>, + a não ser que o arquivo informado já tenha sido + incluído, não refazendo a operação novamente. Como o nome sugere, + ele será incluído apenas uma vez. + </para> + <para> + <function>include_once</function> pode ser utilizado nos casos em + que o mesmo arquivo pode acabar sendo incluído mais de uma vez durante a + execução de um script em particular, quando na verdade ele só pode ser + incluído apenas uma para evitar problemas com redefinições de funções, + alterações nos valores de variáveis, etc. + </para> + <para> + Para maiores informações utilizando <function>require_once</function> e + <function>include_once</function>, veja o código do + <ulink url="&url.php.pear;">PEAR</ulink> incluído nas + últimas distribuições do código fonte do PHP. </para> + <note> + <para> + <function>include_once</function> foi acrescentado a partir PHP 4.0.1pl2 + </para> + </note> <para> - See also: <function>require</function>, - <function>include</function>, <function>require_once</function>, + Veja também: <function>include</function>, + <function>require</function>, <function>require_once</function>, <function>get_required_files</function>, - <function>get_included_files</function>, <function>readfile</function>, - and <function>virtual</function>. + <function>get_included_files</function>, <function>readfile</function> + e <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 + +<!-- 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 indent-tabs-mode:nil - sgml-parent-document:nil - sgml-default-dtd-file:"../../manual.ced" - sgml-exposed-tags:nil - sgml-local-catalogs:nil - sgml-local-ecat-files:nil - End: - --> - \ No newline at end of file +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 +-->