1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288
|
<?xml version="1.0" encoding="iso-8859-1"?>
<chapter id="control-structures">
<title>Estruturas de Controle</title>
<simpara>
Qualquer script PHP construdo por uma srie de comandos. Um comando
pode ser uma atribuio, uma chamada de funo, um 'loop', um comando
condicional, ou mesmo um comando que no faz nada( um comando vazio).
Comandos geralmente terminam com um ponto-e-vrgula. Alm disso, os
comandos podem ser agrupados em um grupo de comandos atravs do encapsulamento
de um grupo de comandos com colchetes. Um grupo de comandos um comando
tambm. Os vrios tipos de comandos so descritos neste captulo.
</simpara>
<sect1 id="control-structures.if">
<title><literal>if</literal></title>
<para>
A construo <literal>if</literal> uma das mais importantes implementaes de
muitas linguagens, incluindo o PHP. Ela permite a execuo condicional de fragmentos
de cdigo. O PHP implementa uma estrutura <literal>if</literal>
que similar quela do C:
<informalexample>
<programlisting>
if (expr)
statement
</programlisting>
</informalexample>
</para>
<simpara>
Como descrito na seo sobre expresses, 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.
</simpara>
<para>
Os exemplos a seguir mostrariam <computeroutput>a maior que
b</computeroutput> se <replaceable>$a</replaceable> for maior que
<replaceable>$b</replaceable>:
<informalexample>
<programlisting role="php">
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, no h necessidade de englobar cada comando com uma clusula
<literal>if</literal>. Em vez disso, voc pode agrupar vrios comandos em um grupo de
comandos. Por exemplo, este cdigo mostraria <computeroutput>a maior que b</computeroutput>
se <replaceable>$a</replaceable> for maior que
<replaceable>$b</replaceable>, e ento atribuiria o valor de
<replaceable>$a</replaceable> para <replaceable>$b</replaceable>:
<informalexample>
<programlisting role="php">
if ($a > $b) {
print "a maior que b";
$b = $a;
}
</programlisting>
</informalexample>
</para>
<simpara>
Comandos 'if' podem ser aninhados indefinidamente dentro de outros comandos
<literal>if</literal>, o que faz com que voc complete a flexibilidade para a
execuo condicional de vrias 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 condio for encontrada, e
e um comando diferente se a condio no 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 expresso no comando
<literal>if</literal> seja avaliada como &false;. Por exemplo, o cdigo a
seguir mostraria <computeroutput>a maior que b</computeroutput> se <replaceable>$a</replaceable>
for maior que <replaceable>$b</replaceable>, e <computeroutput>a NO maior que
b</computeroutput> caso contrrio:
<informalexample>
<programlisting role="php">
if ($a > $b) {
print "a maior que b";
} else {
print "a NO maior que b";
}
</programlisting>
</informalexample>
O comando <literal>else</literal> s executado se a expresso
<literal>if</literal> for avaliada como
&false;, e se houver qualquer expresso
<literal>elseif</literal> - somente se eles forem avaliadas como
&false; tambm (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 combinao
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 expresso
<literal>if</literal> original ser avaliada como
&false;. Porm, ao contrrio de
<literal>else</literal>, ele executar aquela expresso alternativa
somente se a expresso condicional do <literal>elseif</literal> for
avaliada como &true;. Por exemplo, o cdigo a seguir
mostraria <computeroutput>a maior que
b</computeroutput>, <computeroutput>a igual a b</computeroutput>
ou <computeroutput>a menor que b</computeroutput>:
<informalexample>
<programlisting role="php">
if ($a > $b) {
print "a maior que b";
} elseif ($a == $b) {
print "a igual a b";
} else {
print "a menor que b";
}
</programlisting>
</informalexample>
</para>
<simpara>
Podem haver vrios <literal>elseif</literal>s dentro do mesmo comando
<literal>if</literal>. A primeira expresso
<literal>elseif</literal> (se houver) que for avaliada como
&true; ser executada. Em PHP, voc tambm pode escrever
'else if' (em duas palavras) e o comportamento ser indntico a um
'elseif' (em uma s palavra). O significado sinttico ligeiramente diferente
(se voc est familiarizado com C, isto tem o mesmo comportamento),
mas o resultado que ambos resultariam exatamente no mesmo comportamento.
</simpara>
<simpara>
O comando <literal>elseif</literal> s executado se a expresso
<literal>if</literal> precedente e quaisquer expresses
<literal>elseif</literal> precedentes forem avaliadas como
&false;, e a expresso
<literal>elseif</literal> corrente 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 bsica 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
<literal>endswitch;</literal>, respectivamente.
<informalexample>
<programlisting role="php">
<?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
<literal>if</literal> escrito na sintaxe alternativa.
O bloco HTML seria mostrado somente se $a igual a 5.
</simpara>
<para>
A sintaxe alternativa se aplica a <literal>else</literal> e
<literal>elseif</literal> tambm. A seguir vem uma estrutura
<literal>if</literal> com <literal>elseif</literal> e
<literal>else</literal> no formato alternativo:
<informalexample>
<programlisting role="php">
if ($a == 5):
print "a igual a 5";
print "...";
elseif ($a == 6):
print "a igual a 6";
print "!!!";
else:
print "a no 5 nem 6";
endif;
</programlisting>
</informalexample>
</para>
<para>
Veja tambm <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>
<sect1 id="control-structures.while">
<title><literal>while</literal></title>
<para>
Loops <literal>while</literal> so o tipo mais simples de criar um 'loop' em
PHP. Eles se comportam como seus compatveis em C. O formato bsico de um comando
<literal>while</literal> :
<informalexample>
<programlisting>
while (expr) statement
</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 expresso
<literal>while</literal> avaliada como
&true;. O valor da expresso verificada cada vez que se passa
no comeo do 'loop', desta forma mesmo que este valor mude durante a execuo do(s)
comando(s) aninhado(s), a execuo no parar at que o fim da iterao (cada vez que o
PHP roda os comandos dentro do 'loop' uma iterao). s vezes, se a expresso
<literal>while</literal> avaliada como &false; logo no incio,
o(s) comando(s) aninhado(s) no ser(o) rodado(s) nem uma vez sequer.
</simpara>
<para>
Como no comando <literal>if</literal>, voc pode agrupar mltiplos comandos dentro
do mesmo 'loop' <literal>while</literal> englobando um grupo de comandos com
colchetes, ou usando a sintaxe alternativa:
<informalexample>
<programlisting>
while (expr): statement ... endwhile;
</programlisting>
</informalexample>
</para>
<para>
Os exemplos a seguir so idnticos, e ambos imprimem nmeros de 1 to 10:
<informalexample>
<programlisting>
/* exemplo 1 */
$i = 1;
while ($i <= 10) {
print $i++; /* o valor impresso ser
$i antes do incremento
(ps-incremento) */
}
/* exemplo 2 */
$i = 1;
while ($i <= 10):
print $i;
$i++;
endwhile;
</programlisting>
</informalexample>
</para>
</sect1>
<sect1 id="control-structures.do.while">
<title><literal>do..while</literal></title>
<simpara>
Loops <literal>do..while</literal> so bem similares aos 'loops'
<literal>while</literal>, exceto pelo fato de que expresses-verdade
so verificadas no fim de cada iterao em vez de no comeo.
A diferena principal dos 'loops' <literal>while</literal> regulares que
a primeira iterao de um 'loop' <literal>do..while</literal> garantidamente
rodada (a expresso-verdade s verificada no fim da iterao), enquanto que
ele pode no rodar necessariamente em um 'loop'
<literal>while</literal> regular (a expresso-verdade verificada no comeo de
cada iterao, se ela avaliada como
&false; logo no comeo, a execuo do 'loop' terminaria
imediatamente).
</simpara>
<para>
H apenas uma sintaxe para 'loops' <literal>do..while</literal>:
<informalexample>
<programlisting role="php">
$i = 0;
do {
print $i;
} while ($i>0);
</programlisting>
</informalexample>
</para>
<simpara>
O 'loop' acima rodaria exatamente uma vez, desde que depois da primeira
iterao, quando a expresso-verdade verificada, ela avaliada como
&false; ($i no maior que zero 0) e a execuo do 'loop'
termina.
</simpara>
<para>
Usurios avanados de C podem estar familiarizados com o uso diferenciado do
'loop' <literal>do..while</literal>, para permitir o fim da execuo no
meio dos blocos de cdigo, englobando-os com
<literal>do..while</literal>(0), e usando o comando <link
linkend="control-structures.break"><literal>break</literal></link>
statement. O fragmento de cdigo a seguir demonstra isso:
<informalexample>
<programlisting role="php">
do {
if ($i < 5) {
print "i no grande o suficiente";
break;
}
$i *= $factor;
if ($i < $minimum_limit) {
break;
}
print "i est correto";
...process i...
} while(0);
</programlisting>
</informalexample>
</para>
<simpara>
No se preocupe se voc no entendeu isto da forma certa ou de jeito nenhum.
Voc pode codificar scripts e mesmo poderosos scripts sem usar essa
`opo'.
</simpara>
</sect1>
<sect1 id="control-structures.for">
<title><literal>for</literal></title>
<para>
Loops <literal>for</literal> so os 'loops' mais complexos em PHP.
Eles se comportam como os seus compatveis em C. A sintaxe de um 'loop'
<literal>for</literal> :
<informalexample>
<programlisting>
for (expr1; expr2; expr3) statement
</programlisting>
</informalexample>
</para>
<simpara>
A primeira expresso (<replaceable>expr1</replaceable>)
avaliada (executada) uma vez incondicionalmente no comeo do 'loop'.
</simpara>
<simpara>
No comeo de cada iterao, <replaceable>expr2</replaceable> avaliada.
Se ela avaliada como &true;, o 'loop' continua e o(s)
comando(s) aninhado(s) (so) executado(s). Se avaliada como
&false;, a execuo do 'loop' termina.
</simpara>
<simpara>
No fim de cada iterao, <replaceable>expr3</replaceable> avaliada
(executada).
</simpara>
<simpara>
Cada uma das expresses pode ser vazia.
<replaceable>expr2</replaceable> vazia significa que o 'loop' pode rodar
indefinidamente (PHP considera-a implicitamente como
&true;, como em C). Isto pode no ser to intil quanto
voc pode pensar, pois frequentemente voc pode querer terminar o 'loop'
usando um comando <link
linkend="control-structures.break"><literal>break</literal></link>
condicional em vez de usar a expresso-verdade do <literal>for</literal>.
</simpara>
<para>
Considere os seguintes exemplos. Todos eles mostram nmeros de 1 a 10:
<informalexample>
<programlisting role="php">
/* exemplo 1 */
for ($i = 1; $i <= 10; $i++) {
print $i;
}
/* exemplo 2 */
for ($i = 1;;$i++) {
if ($i > 10) {
break;
}
print $i;
}
/* exemplo 3 */
$i = 1;
for (;;) {
if ($i > 10) {
break;
}
print $i;
$i++;
}
/* exemplo 4 */
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 possvel utilizao de expresses vazias em 'loops'
<literal>for</literal> se torna prtico em muitas ocasies.
</simpara>
<para>
O PHP tambm suporta a "sintaxe de dois-pontos" alternativa para 'loops'
<literal>for</literal>.
<informalexample>
<programlisting>
for (expr1; expr2; expr3): statement; ...; endfor;
</programlisting>
</informalexample>
</para>
<para>
Outras linguagens tm um comando <literal>foreach</literal> para varrer uma
matriz ou tabela de hashing. O PHP3 no tem uma construo deste tipo; O PHP4 tem
(veja <link linkend="control-structures.foreach">foreach</link>). Em PHP3,
voc pode combinar <link linkend="control-structures.while">while</link>
com as funes <function>list</function> e <function>each</function> para
obter o mesmo efeito. Veja a documentao para estas funes para ter um
exemplo.
</para>
</sect1>
<sect1 id="control-structures.foreach">
<title><literal>foreach</literal></title>
<para>
O PHP4 (no o PHP3) inclui uma construo <literal>foreach</literal>,
muito parecido com o perl e outras linguagens. Isto simplesmente oferece uma
maneira fcil de iterar sobre matrizes. H duas sintaxes; a segunda uma
extenso menor, mas til, da primeira:
<informalexample>
<programlisting>
foreach(array_expression as $value) statement
foreach(array_expression as $key => $value) statement
</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 atribudo a <literal>$value</literal> e o ponteiro interno da
matriz avanado em uma posio (assim, no prximo 'loop' voc estar
olhando para o prximo elemento).
</simpara>
<simpara>
A segunda forma faz a mesma coisa, exceto pelo fato de que a chave do elemento
corrente ser atribudo varivel <literal>$key</literal> em cada 'loop'.
</simpara>
<para>
<note>
<para>
Quando o <literal>foreach</literal> inicia sua primeira execuo, o ponteiro
interno da matriz zerado automaticamente para o primeiro elemento da matriz.
Isto significa que voc no precisa chamar
<function>reset</function> antes de um 'loop' <literal>foreach</literal>.
</para>
</note>
</para>
<para>
<note>
<para>
Note tambm que <literal>foreach</literal> opera sobre uma cpia da matriz
especificada, no na prpria matriz, portanto o ponteiro da matriz no
modificado como na construo 'each'.
</para>
</note>
</para>
<para>
Voc pode ter notado que os seguintes itens so funcionalmente idnticos:
<informalexample>
<programlisting role="php">
reset ($arr);
while (list(, $value) = each ($arr)) {
echo "Value: $value<br>\n";
}
foreach ($arr as $value) {
echo "Value: $value<br>\n";
}
</programlisting>
</informalexample>
Os seguintes tanbm so funcionalmente idnticos:
<informalexample>
<programlisting role="php">
reset ($arr);
while (list($key, $value) = each ($arr)) {
echo "Key: $key; Value: $value<br>\n";
}
foreach ($arr as $key => $value) {
echo "Key: $key; Value: $value<br>\n";
}
</programlisting>
</informalexample>
</para>
<para>
Mais alguns exemplos para demonstrar os usos:
<informalexample>
<programlisting role="php">
/* exemplo de foreach 1: s valor */
$a = array (1, 2, 3, 17);
foreach ($a as $v) {
print "Valor corrente de \$a: $v.\n";
}
/* exemplo de foreach 2: valor (com a chave impressa para ilustrao) */
$a = array (1, 2, 3, 17);
$i = 0; /* s para propsito de ilustrao */
foreach($a as $v) {
print "\$a[$i] => $k.\n";
}
/* exemplo de foreach 3: chave e valor */
$a = array (
"one" => 1,
"two" => 2,
"three" => 3,
"seventeen" => 17
);
foreach($a as $k => $v) {
print "\$a[$k] => $v.\n";
}
</programlisting>
</informalexample>
</para>
</sect1>
<sect1 id="control-structures.break">
<title><literal>break</literal></title>
<simpara>
<literal>break</literal> termina a execuo da estrutura
<literal>for</literal>, <literal>while</literal>, ou
<literal>switch</literal> corrente.
</simpara>
<simpara>
<literal>break</literal> aceita um argumento numrico 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 tambm poderia escrever 'break 1;' aqui. */
}
echo "$val<br>\n";
}
/* Usando o argumento opcional. */
$i = 0;
while ( ++$i ) {
switch ( $i ) {
case 5:
echo "At 5<br>\n";
break 1; /* sai somento de 'switch'. */
case 10:
echo "At 10; quitting<br>\n";
break 2; /* sai de 'switch' e de '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 iterao do 'loop' corrente e continuar a execuo
no incio da prxima iterao.
</simpara>
<simpara>
<literal>continue</literal> aceita um argumento numrico opcional que diz
a ele de quantos nveis de 'loops' englobados ele deveria saltar at o fim.
</simpara>
<para>
<informalexample>
<programlisting role="php">
while (list ($key, $value) = each ($arr)) {
if (!($key % 2)) { // salta membros mpares
continue;
}
do_something_odd ($value);
}
$i = 0;
while ($i++ < 5) {
echo "Mais externo<br>\n";
while (1) {
echo " Meio<br>\n";
while (1) {
echo " Inner<br>\n";
continue 3;
}
echo "This never gets output.<br>\n";
}
echo "Neither does this.<br>\n";
}
</programlisting>
</informalexample>
</para>
</sect1>
<sect1 id="control-structures.switch">
<title><literal>switch</literal></title>
<simpara>
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:
<informalexample>
<programlisting role="php">
if ($i == 0) {
print "i equals 0";
}
if ($i == 1) {
print "i equals 1";
}
if ($i == 2) {
print "i equals 2";
}
switch ($i) {
case 0:
print "i equals 0";
break;
case 1:
print "i equals 1";
break;
case 2:
print "i equals 2";
break;
}
</programlisting>
</informalexample>
</para>
<para>
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:
<informalexample>
<programlisting role="php">
switch ($i) {
case 0:
print "i equals 0";
case 1:
print "i equals 1";
case 2:
print "i equals 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).
</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.
</simpara>
<para>
The statement list for a case can also be empty, which simply
passes control into the statement list for the next case.
<informalexample>
<programlisting role="php">
switch ($i) {
case 0:
case 1:
case 2:
print "i is less than 3 but not negative";
break;
case 3:
print "i is 3";
}
</programlisting>
</informalexample>
</para>
<para>
A special case is the default case. This case matches anything
that wasn't matched by the other cases. For example:
<informalexample>
<programlisting role="php">
switch ($i) {
case 0:
print "i equals 0";
break;
case 1:
print "i equals 1";
break;
case 2:
print "i equals 2";
break;
default:
print "i is not equal to 0, 1 or 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.
</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> .
<informalexample>
<programlisting role="php">
switch ($i):
case 0:
print "i equals 0";
break;
case 1:
print "i equals 1";
break;
case 2:
print "i equals 2";
break;
default:
print "i is not equal to 0, 1 or 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>
<simpara>
If "URL fopen wrappers" are enabled in PHP (which they are in the
default configuration), you can specify the file to be
<function>require</function>ed using an URL instead of a local
pathname. See <link linkend="features.remote-files">Remote
files</link> and <function>fopen</function> for more information.
</simpara>
<simpara>
An important note about how this works is that when a file is
<function>include</function>ed or <function>require</function>ed,
parsing drops out of PHP mode and into HTML mode at the beginning
of the target file, and resumes PHP mode again at the end. For
this reason, any code inside the target file which should be
executed as PHP code must be enclosed within <link
linkend="language.basic-syntax.phpmode">valid PHP start and end
tags</link>.
</simpara>
<simpara>
<function>require</function> is not actually a function in PHP;
rather, it is a language construct. It is subject to some
different rules than functions are. For instance,
<function>require</function> is not subject to any containing
control structures. For another, it does not return any value;
attempting to read a return value from a
<function>require</function> call results in a parse error.
</simpara>
<simpara>
Unlike <function>include</function>, <function>require</function>
will <emphasis>always</emphasis> read in the target file,
<emphasis>even if the line it's on never executes</emphasis>. If
you want to conditionally include a file, use
<function>include</function>. The conditional statement won't
affect the <function>require</function>. However, if the line on
which the <function>require</function> occurs is not executed,
neither will any of the code in the target file be executed.
</simpara>
<simpara>
Similarly, looping structures do not affect the behaviour of
<function>require</function>. Although the code contained in the
target file is still subject to the loop, the
<function>require</function> itself happens only once.
</simpara>
<para>
This means that you can't put a <function>require</function>
statement inside of a loop structure and expect it to include the
contents of a different file on each iteration. To do that, use an
<function>include</function> statement.
<informalexample>
<programlisting role="php">
require ('header.inc');
</programlisting>
</informalexample>
</para>
<simpara>
When a file is <function>require</function>ed, the code it
contains inherits the variable scope of the line on which the
<function>require</function> occurs. Any variables available at
that line in the calling file will be available within the called
file. If the <function>require</function> occurs inside a
function within the calling file, then all of the code contained
in the called file will behave as though it had been defined
inside that function.
</simpara>
<para>
If the <function>require</function>ed file is called via HTTP
using the fopen wrappers, and if the target server interprets the
target file as PHP code, variables may be passed to the
<function>require</function>ed file using an URL request string as
used with HTTP GET. This is not strictly speaking the same thing
as <function>require</function>ing the file and having it inherit
the parent file's variable scope; the script is actually being run
on the remote server and the result is then being included into
the local script.
<informalexample>
<programlisting role="php">
/* This example assumes that someserver is configured to parse .php
* files and not .txt files. Also, 'works' here means that the variables
* $varone and $vartwo are available within the require()ed file. */
/* Won't work; file.txt wasn't handled by someserver. */
require ("http://someserver/file.txt?varone=1&vartwo=2");
/* Won't work; looks for a file named 'file.php?varone=1&vartwo=2'
* on the local filesystem. */
require ("file.php?varone=1&vartwo=2");
/* Works. */
require ("http://someserver/file.php?varone=1&vartwo=2");
$varone = 1;
$vartwo = 2;
require ("file.txt"); /* Works. */
require ("file.php"); /* Works. */
</programlisting>
</informalexample>
</para>
<simpara>
In PHP 3, it is possible to execute a <literal>return</literal>
statement inside a <function>require</function>ed file, as long as
that statement occurs in the global scope of the
<function>require</function>ed file. It may not occur within any
block (meaning inside braces ({}). In PHP 4, however, this ability
has been discontinued. If you need this functionality, see
<function>include</function>.
</simpara>
<simpara>
See also <function>include</function>, <function>require_once</function>,
<function>include_once</function>, <function>readfile</function>,
and <function>virtual</function>.
</simpara>
</sect1>
<sect1 id="function.include">
<title><function>include</function></title>
<simpara>
The <function>include</function> statement includes and evaluates
the specified file.
</simpara>
<simpara>
If "URL fopen wrappers" are enabled in PHP (which they are in the
default configuration), you can specify the file to be
<function>include</function>ed using an URL instead of a local
pathname. See <link linkend="features.remote-files">Remote
files</link> and <function>fopen</function> for more information.
</simpara>
<simpara>
An important note about how this works is that when a file is
<function>include</function>ed or <function>require</function>ed,
parsing drops out of PHP mode and into HTML mode at the beginning
of the target file, and resumes again at the end. For this reason,
any code inside the target file which should be executed as PHP
code must be enclosed within <link
linkend="language.basic-syntax.phpmode">valid PHP start and end
tags</link>.
</simpara>
<para>
This happens each time the <function>include</function> statement
is encountered, so you can use an <function>include</function>
statement within a looping structure to include a number of
different files.
<informalexample>
<programlisting role="php">
$files = array ('first.inc', 'second.inc', 'third.inc');
for ($i = 0; $i < count($files); $i++) {
include $files[$i];
}
</programlisting>
</informalexample>
</para>
<para>
<function>include</function> differs from
<function>require</function> in that the include statement is
re-evaluated each time it is encountered (and only when it is
being executed), whereas the <function>require</function>
statement is replaced by the required file when it is first
encountered, whether the contents of the file will be evaluated or
not (for example, if it is inside an <link
linkend="control-structures.if">if</link> statement whose
condition evaluated to &false;).
</para>
<para>
Because <function>include</function> is a special language
construct, you must enclose it within a statement block if it is
inside a conditional block.
<informalexample>
<programlisting role="php">
/* This is WRONG and will not work as desired. */
if ($condition)
include($file);
else
include($other);
/* This is CORRECT. */
if ($condition) {
include($file);
} else {
include($other);
}
</programlisting>
</informalexample>
</para>
<simpara>
In both PHP 3 and PHP 4, it is possible to execute a
<literal>return</literal> statement inside an
<function>include</function>ed file, in order to terminate
processing in that file and return to the script which called
it. Some differences in the way this works exist, however. The
first is that in PHP 3, the <literal>return</literal> may not
appear inside a block unless it's a function block, in which case
the <literal>return</literal> applies to that function and not the
whole file. In PHP 4, however, this restriction does not
exist. Also, PHP 4 allows you to return values from
<function>include</function>ed files. You can take the value of
the <function>include</function> call as you would a normal
function. This generates a parse error in PHP 3.
</simpara>
<example>
<title><function>include</function> in PHP 3 and PHP 4</title>
<para>
Assume the existence of the following file (named
<filename>test.inc</filename>) in the same directory as the main
file:
<programlisting role="php">
<?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.
</simpara>
<para>
If the <function>include</function>ed file is called via HTTP
using the fopen wrappers, and if the target server interprets the
target file as PHP code, variables may be passed to the
<function>include</function>ed file using an URL request string as
used with HTTP GET. This is not strictly speaking the same thing
as <function>include</function>ing the file and having it inherit
the parent file's variable scope; the script is actually being run
on the remote server and the result is then being included into
the local script.
<informalexample>
<programlisting role="php">
/* This example assumes that someserver is configured to parse .php
* files and not .txt files. Also, 'works' here means that the variables
* $varone and $vartwo are available within the include()ed file. */
/* Won't work; file.txt wasn't handled by someserver. */
include ("http://someserver/file.txt?varone=1&vartwo=2");
/* Won't work; looks for a file named 'file.php?varone=1&vartwo=2'
* on the local filesystem. */
include ("file.php?varone=1&vartwo=2");
/* Works. */
include ("http://someserver/file.php?varone=1&vartwo=2");
$varone = 1;
$vartwo = 2;
include ("file.txt"); /* Works. */
include ("file.php"); /* Works. */
</programlisting>
</informalexample>
</para>
<simpara>
See also <function>require</function>, <function>require_once</function>,
<function>include_once</function>, <function>readfile</function>,
and <function>virtual</function>.
</simpara>
</sect1>
<sect1 id="function.require-once">
<title><function>require_once</function></title>
<para>
The <function>require_once</function> statement replaces
itself with the specified file, much like the C preprocessor's
<literal>#include</literal> works, and in that respect is
similar to the <function>require</function> statement. The main
difference is that in an inclusion chain, the use of
<function>require_once</function> will assure that the code is
added to your script only once, and avoid clashes with variable
values or function names that can happen.
</para>
<para>
For example, if you create the following 2 include files
<literal>utils.inc</literal> and <literal>foolib.inc</literal>
<example>
<title>utils.inc</title>
<programlisting role="php">
<?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.
</para>
<para>
See also: <function>require</function>,
<function>include</function>, <function>include_once</function>,
<function>get_required_files</function>,
<function>get_included_files</function>, <function>readfile</function>,
and <function>virtual</function>.
</para>
</sect1>
<sect1 id="function.include-once">
<title><function>include_once</function></title>
<para>
The <function>include_once</function> statement includes and evaluates
the specified file during the execution of the script.
This is a behavior similar to the <function>include</function> statement,
with the important difference that if the code from a file has already
been included, it will not be included again.
</para>
<para>
As mentioned in the <function>require_once</function> description, the
<function>include_once</function> should be used in the cases in which
the same file might be included and evaluated more than once during a
particular execution of a script, and you want to be sure that it is
included exactly once to avoid problems with function redefinitions,
variable value reassignments, etc.
</para>
<para>
For more examples on using <function>require_once</function> and
<function>include_once</function>, look at the PEAR code included in
the latest PHP source code distributions.
</para>
<para>
<function>include_once</function> was added in PHP 4.0.1pl2
</para>
<para>
See also: <function>require</function>,
<function>include</function>, <function>require_once</function>,
<function>get_required_files</function>,
<function>get_included_files</function>, <function>readfile</function>,
and <function>virtual</function>.
</para>
</sect1>
</chapter>
<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
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:
-->
|