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
+-->