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
|
<chapter id="lang-const">
<title>Language constructs</title>
<simpara>
Any PHP 3 script is built out of a series of statements. A
statement can be an assignment, a function call, a loop, a
conditional statement of even a statement that does nothing (an
empty statement). Statements usually end with a semicolon. In
addition, statements can be grouped into a statement-group by
encapsulating a group of statements with curly braces. A
statement-group is a statement by itself as well. The various
statement types are described in this chapter.
</simpara>
<sect1 id="expressions">
<title>Expressions</title>
<simpara>
Expressions are the most important building stones of PHP. In PHP
3.0, almost anything you write is an expression. The simplest yet
most accurate way to define an expressions is "anything that has a
value".
<simpara>
Simple examples that come in mind are constants and variables.
When you type "$a = 5", you're assigning '5' into $a. '5',
obviously, has the value 5, or in other words '5' is an expression
with the value of 5 (in this case, '5' is an integer constant).
<simpara>
After this assignment, you'd expect $a's value to be 5 as
well, so if you wrote $b = $a, you'd expect it to behave just as
if you wrote $b = 5. In other words, $a is an expression with the
value of 5 as well. If everything works right, this is exactly
what will happen.
<para>
Slightly more complex examples for expressions are functions. For
instance, consider the following function:
<informalexample>
<programlisting>
function foo()
{
return 5;
}
</programlisting>
</informalexample>
<simpara>
Assuming you're familiar with the concept of functions (if you're
not, take a look at the chapter about functions), you'd assume
that typing <literal>$c = foo()</literal> is essentially just like
writing <literal>$c = 5</literal>, and you're right. Functions
are expressions with the value of their return value. Since foo()
returns 5, the value of the expression 'foo()' is 5. Usually
functions don't just return a static value but compute something.
<simpara>
Of course, values in PHP don't have to be integers, and very often
they aren't. PHP supports 3 scalar value types: integer values,
floating point values and string values (scalar values are values that
you can't 'break' into smaller pieces, unlike arrays, for instance).
PHP also supports two composite (non-scalar) types: arrays and
objects. Each of these value types can be assigned into variables or
returned from functions.
<simpara>
So far, users of PHP/FI 2 shouldn't feel any change. However, PHP
3 takes expressions much further, in the same way many other
languages do. PHP 3 is an expression-oriented language, in the
sense that almost everything is an expression. Consider the
example we've already dealt with, '$a = 5'. It's easy to see that
there are two values involved here, the value of the integer
constant '5', and the value of $a which is being updated to 5 as
well. But the truth is that there's one additional value involved
here, and that's the value of the assignment itself. The
assignment itself evaluates to the assigned value, in this case 5.
In practice, it means that '$a = 5', regardless of what it does,
is an expression with the value 5. Thus, writing something like
'$b = ($a = 5)' is like writing '$a = 5; $b = 5;' (a semicolon
marks the end of a statement). Since assignments are parsed in a
right to left order, you can also write '$b = $a = 5'.
<simpara>
Another good example of expression orientation is pre- and
post-increment and decrement. Users of PHP/FI 2 and many other
languages may be familiar with the notation of variable++ and
variable--. These are increment and decrement operators. In
PHP/FI 2, the statement '$a++' has no value (is not an
expression), and thus you can't assign it or use it in any way.
PHP 3 enhances the increment/decrement capabilities by making
these expressions as well, like in C. In PHP 3, like in C, there
are two types of increment - pre-increment and post-increment.
Both pre-increment and post-increment essentially increment the
variable, and the effect on the variable is idential. The
difference is with the value of the increment expression.
Pre-increment, which is written '++$variable', evaluates to the
incremented value (PHP increments the variable before reading its
value, thus the name 'pre-increment'). Post-increment, which is
written '$variable++' evaluates to the original value of
$variable, before it was incremented (PHP increments the variable
after reading its value, thus the name 'post-increment').
<simpara>
A very common type of expressions are comparison expressions.
These expressions evaluate to either 0 or 1, meaning FALSE or TRUE
(respectively). PHP supports > (bigger than), >= (bigger than or
equal to), == (equal), < (smaller than) and <= (smaller than or
equal to). These expressions are most commonly used inside
conditional execution, such as IF statements.
<simpara>
The last example of expressions we'll deal with here is combined
operator-assignment expressions. You already know that if you
want to increment $a by 1, you can simply write '$a++' or '++$a'.
But what if you want to add more than one to it, for instance 3?
You could write '$a++' multiple times, but this is obviously not a
very efficient or comfortable way. A much more common practice is
to write '$a = $a + 3'. '$a + 3' evaluates to the value of $a
plus 3, and is assigned back into $a, which results in
incrementing $a by 3. In PHP 3, as in several other languages
like C, you can write this in a shorter way, which with time would
become clearer and quicker to understand as well. Adding 3 to the
current value of $a can be written '$a += 3'. This means exactly
"take the value of $a, add 3 to it, and assign it back into $a".
In addition to being shorter and clearer, this also results in
faster execution. The value of '$a += 3', like the value of a
regular assignment, is the assigned value. Notice that it is NOT
3, but the combined value of $a plus 3 (this is the value that's
assigned into $a). Any two-place operator can be used in this
operator-assignment mode, for example '$a -= 5' (subtract 5 from
the value of $a), '$b *= 7' (multiply the value of $b by 7), etc.
<para>
The following example should help you understand pre- and
post-increment and expressions in general a bit better:
<informalexample>
<programlisting>
function double($i)
{
return $i*2;
}
$b = $a = 5; /* assign the value five into the variable $a and $b */
$c = $a++; /* post-increment, assign original value of $a (5) to $c */
$e = $d = ++$b; /* pre-increment, assign the incremented value of $b (6) to $d and $e */
/* at this point, both $d and $e are equal to 6 */
$f = double($d++); /* assign twice the value of $d <emphasis>before</emphasis> the increment, 2*6 = 12 to $f */
$g = double($++e); /* assign twice the value of $e <emphasis>after</emphasis> the increment, 2*7 = 14 to $f */
$h = $g += 10; /* first, $g is incremented by 10 and ends with the value of 24.
the value of the assignment (24) is then assigned into $h,
and $h ends with the value of 24 as well. */
</programlisting></informalexample>
<simpara>
In the beginning of the chapter we said that we'll be describing
the various statement types, and as promised, expressions can be
statements. However, not every expression is a statement. In
this case, a statement has the form of 'expr' ';' that is, an
expression followed by a semicolon. In '$b=$a=5;', $a=5 is a
valid expression, but it's not a statement by itself. '$b=$a=5;'
however is a valid statement.
<simpara>
One last thing worth mentioning is the truth value of expressions.
In many events, mainly in conditional execution and loops, you're
not interested in the specific value of the expression, but only
care about whether it means TRUE or FALSE (PHP doesn't have a
dedicated boolean type). The truth value of expressions in PHP is
calculated in a similar way to perl. Any numeric non-zero numeric
value is TRUE, zero is FALSE. Be sure to note that negative
values are non-zero and are thus considered TRUE! The empty
string and the string "0" are FALSE; all other strings are TRUE.
With non-scalar values (arrays and objects) - if the value
contains no elements it's considered FALSE, otherwise it's
considered TRUE.
<simpara>
PHP 3 provides a full and powerful implementation of expressions,
and documenting it entirely goes beyond the scope of this manual.
The above examples should give you a good idea about what
expressions are and how you can construct useful expressions.
Throughout the rest of this manual we'll write 'expr' to mark any
valid PHP3 expression.
<sect1 id="construct.if">
<title>IF</title>
<para>
The IF construct is one of the most important features of many
languages, PHP included. It allows for conditional execution of
code fragments. PHP features an IF sentence that is similar to
that of C:
<informalexample><programlisting>
if (expr)
statement
</programlisting></informalexample>
<simpara>
As described in the section about expressions, expr is evaluated
to its truth value. If expr evaluates to TRUE, PHP will execute
statement, and if it evaluates to FALSE - it'll ignore it.
<para>
The following example would display 'a is bigger than b' if $a is
bigger than $b:
<informalexample><programlisting>
if ($a > $b)
print "a is bigger than b";
</programlisting></informalexample>
<para>
Often you'd want to have more than one statement to be executed
conditionally. Of course, there's no need to wrap each statement
with an IF clause. Instead, you can group several statements into
a statement group. For example, this code would display 'a is
bigger than b' if $a is bigger than $b, and would then assign the
value of $a into $b:
<informalexample><programlisting>
if ($a>$b) {
print "a is bigger than b";
$b = $a;
}
</programlisting></informalexample>
<simpara>
If statements can be nested indefinitely within other IF
statements, which provides you with complete flexibility for
conditional execution of the various parts of your program.
</sect1>
<sect1 id="construct.else">
<title>ELSE</title>
<para>
Often you'd want to execute a statement if a certain condition is
met, and a different statement if the condition is not met. This
is what ELSE is for. ELSE extends an IF statement to execute a
statement in case the expression in the IF statement evaluates to
FALSE. For example, the following code would display 'a is bigger
than b' if $a is bigger than $b, and 'a is NOT bigger than b'
otherwise:
<informalexample><programlisting>
if ($a>$b) {
print "a is bigger than b";
} else {
print "a is NOT bigger than b";
}
</programlisting></informalexample>
The ELSE statement is only executed if the IF expression evaluated
to FALSE, and if there were any ELSEIF expressions - only if they
evaluated to FALSE as well (see below).
<sect1 id="construct.elseif">
<title>ELSEIF</title>
<para>ELSEIF, as its name suggests, is a combination of IF and
ELSE. Like ELSE, it extends an IF statement to execute a
different statement in case the original IF expression evaluates
to FALSE. However, unlike ELSE, it will execute that alternative
expression only if the ELSEIF expression evaluates to TRUE. For
example, the following code would display 'a is bigger than b' if
$a>$b, 'a is equal to b' if $a==$b, and 'a is smaller than b' if
$a<$b:
<informalexample><programlisting>
if ($a > $b) {
print "a is bigger than b";
} elseif ($a == $b) {
print "a is equal to b";
} else {
print "a is smaller than b";
}
</programlisting></informalexample>
<simpara>
There may be several ELSEIFs within the same IF statement. The
first ELSEIF expression (if any) that evaluates to TRUE would be
executed. In PHP 3, you can also write 'else if' (in two words)
and the behavior would be identical to the one of 'elseif' (in a
single word). The syntactic meaning is slightly different (if
you're familiar with C, this is the same behavior) but the bottom
line is that both would result in exactly the same behavior.
<simpara>
The ELSEIF statement is only executed if the IF expression and any
previous ELSEIF expressions evaluated to FALSE, and the current
ELSEIF expression evaluated to TRUE.
<sect2>
<title>Alternative syntax for IF statements: IF(): ... ENDIF;</title>
<para>PHP 3 offers a different way to group statements within an IF
statement. This is most commonly used when you nest HTML blocks
inside IF statements, but can be used anywhere. Instead of using
curly braces, the IF(expr) should be followed by a colon, the list
of one or more statements, and end with ENDIF;. Consider the
following example:
<informalexample><programlisting>
<?php if ($a==5): ?>
A = 5
<?php endif; ?>
</programlisting></informalexample>
<simpara>In the above example, the HTML block "A = 5" is nested
within an IF statement written in the alternative syntax. The
HTML block would be displayed only if $a is equal to 5.
<para>The alternative syntax applies to ELSE and ELSEIF (expr) as
well. The following is an IF statement with ELSEIF and ELSE in
the alternative format:
<informalexample><programlisting>
if ($a==5):
print "a equals 5";
print "...";
elseif ($a==6):
print "a equals 6";
print "!!!";
else:
print "a is neither 5 nor 6";
endif;
</programlisting></informalexample>
<sect1 id="construct.while">
<title>WHILE</title>
<para>
WHILE loops are the simplest type of loop in PHP 3. They behave
just like their C counterparts. The basic form of a WHILE
statement is:
<informalexample><programlisting>
WHILE(expr) statement
</programlisting></informalexample>
<simpara>
The meaning of a WHILE statement is simple. It tells PHP to
execute the nested statement(s) repeatedly, as long as the WHILE
expression evaluates to TRUE. The value of the expression is
checked each time at the beginning of the loop, so even if this
value changes during the execution of the nested statement(s),
execution will not stop until the end of the iteration (each time
PHP runs the statements in the loop is one iteration). Sometimes,
if the WHILE expression evaluates to FALSE from the very
beginning, the nested statement(s) won't even be run once.
<para>
Like with the IF statement, you can group multiple statements
within the same WHILE loop by surrounding a group of statements
with curly braces, OR by using the alternate syntax:
<informalexample><programlisting>
WHILE(expr): statement ... ENDWHILE;
</programlisting></informalexample>
<para>
The following examples are identical, and both print numbers from
1 to 10:
<informalexample><programlisting>
/* example 1 */
$i=1;
while ($i<=10) {
print $i++; /* the printed value would be $i before the increment (post-increment) */
}
/* example 2 */
$i=1;
while ($i<=10):
print $i;
$i++;
endwhile;
</programlisting></informalexample>
<sect1 id="construct.do.while">
<title>DO..WHILE</title>
<simpara>
DO..WHILE loops are very similar to WHILE loops, except the truth
expression is checked at the end of each iteration instead of in
the beginning. The main difference from regular WHILE loops is
that the first iteration of a DO..WHILE loop is guarenteed to run
(the truth expression is only checked at the end of the
iteration), whereas it's may not necessarily run with a regular
WHILE loop (the truth expression is checked at the beginning of
each iteration, if it evaluates to FALSE right from the beginning,
the loop execution would end immediately).
<para>
There is just one syntax for DO..WHILE loops:
<informalexample><programlisting>
$i = 0;
do {
print $i;
} while ($i>0);
</programlisting></informalexample>
<simpara>
The above loop would run one time exactly, since after the first
iteration, when truth expression is checked, it evaluates to FALSE
($i is not bigger than 0) and the loop execution ends.
<para>
Advanced C users may be familiar with a different usage of the
DO..WHILE loop, to allow stopping execution in the middle of code
blocks, by encapsulating them with DO..WHILE(0), and using the
BREAK statement. The following code fragment demonstrates this:
<informalexample><programlisting>
do {
if ($i < 5) {
print "i is not big enough";
break;
}
$i *= $factor;
if ($i < $minimum_limit) {
break;
}
print "i is ok";
...process i...
} while(0);
</programlisting></informalexample>
<simpara>
Don't worry if you don't understand this right away or at all.
You can code scripts and even powerful scripts without using this
`feature'.
<sect1 id="construct.for">
<title>FOR</title>
<para>
FOR loops are the most complex loops in PHP. They behave like
their C counterparts. The syntax of a FOR loop is:
<informalexample><programlisting>
FOR (expr1; expr2; expr3) statement
</programlisting></informalexample>
<simpara>
The first expression (expr1) is evaluated (executed)
unconditionally at the beginning of the loop.
<simpara>
In the beginning of each iteration, expr2 is evaluated. If it
evaluates to TRUE, the loop continues and the nested statement(s)
are executed. If it evaluates to FALSE, the execution of the loop
ends.
<simpara>
At the end of each iteration, expr3 is evaluated (executed).
<simpara>
Each of the expressions can be empty. expr2 being empty means the
loop should be run indefinitely (PHP implicitly considers it as
TRUE, like C). This may not be as useless as you might think,
since often you'd want to end the loop using a conditional BREAK
statement instead of using the FOR truth expression.
<para>
Consider the following examples. All of them display numbers from
1 to 10:
<informalexample><programlisting>
/* example 1 */
for ($i=1; $i<=10; $i++) {
print $i;
}
/* example 2 */
for ($i = 1;;$i++) {
if ($i > 10) {
break;
}
print $i;
}
/* example 3 */
$i = 1;
for (;;) {
if ($i > 10) {
break;
}
print $i;
$i++;
}
</programlisting></informalexample>
<simpara>
Of course, the first example appears to be the nicest one, but you
may find that being able to use empty expressions in FOR loops comes
in handy in many occasions.
<para>There is only one format for FOR loops in PHP 3.
<informalexample><programlisting>
FOR(expr): ... ENDFOR; is NOT supported.
</programlisting></informalexample>
<para>
Other languages have a foreach statement to traverse an array
or hash. PHP uses the while statement and the <function>list</function>
and <function>each</function> functions for this. See the documentation
for these functions for an example.
<sect1 id="construct.switch">
<title>SWITCH</title>
<simpara>
The SWITCH 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 SWITCH statement is for.
<para>
The following two examples are two different ways to write the
same thing, one using a series of IF statements, and the other
using the SWITCH statement:
<informalexample><programlisting>
/* example 1 */
if ($i == 0) {
print "i equals 0";
}
if ($i == 1) {
print "i equals 1";
}
if ($i == 2) {
print "i equals 2";
}
/* example 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>
It is important to understand how the SWITCH statement is executed
in order to avoid messups. The SWITCH statement executes line by
line (actually, statement by statement). In the beginning, no
code is executed. Only when a CASE statement is found with a
value that matches the value of the SWITCH expression, PHP begins
to execute the statements. PHP continues to execute the
statements until the end of the SWITCH block, or the first time it
sees a BREAK statement. If you don't write a BREAK 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>
/* example 3 */
switch ($i) {
case 0:
print "i equals 0";
case 1:
print "i equals 1";
case 2:
print "i equals 2";
}
</programlisting></informalexample>
<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 BREAK statements (even though you may
want to avoid supplying them on purpose under certain
circumstances).
<para>
A special case is the default case. This case matches anything
that wasn't matched by the other cases. For example:
<informalexample><programlisting>
/* example 4 */
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>
Another fact worth mentioning is that the CASE expression may be
any expression that evaluates to a scalar type, that is, integer
or real numbers and strings. Arrays or objects won't crash PHP,
but they're meaningless in that context.
<sect1 id="function.require">
<title>REQUIRE</title>
<simpara>
The REQUIRE statement replaces itself with the specified file,
much like the C preprocessor's #include works.
<para>
This means that you can't put a require() 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 INCLUDE
statement.
<informalexample><programlisting>
require('header.inc');
</programlisting></informalexample>
<sect1 id="function.include">
<title>INCLUDE</title>
<simpara>
The INCLUDE statement includes the specified file.
<para>
This happens each time the INCLUDE statement is encountered,
so you can use an INCLUDE statement within a looping structure
to include a number of different file.
<informalexample><programlisting>
$files = array('first.inc', 'second.inc', 'third.inc');
for ($i = 0; $i < count($files); $i++) {
include($files[$i]);
}
</programlisting></informalexample>
<sect1 id="keyword.function">
<title>FUNCTION</title>
<para>
A function may be defined using syntax such as the following:
<informalexample>
<programlisting>
function foo( $arg_1, $arg_2, ..., $arg_n ) {
echo "Example function.\n";
return $retval;
}
</programlisting>
</informalexample>
<simpara>
Any valid PHP3 code may appear inside a function, even other
functions and <link linkend="keyword.class">class</link> definitions.
<sect2 id="keyword.function.return">
<title>Returning values</title>
<para>
Values are returned by using the optional return statement. Any
type may be returned, including lists and objects.
<informalexample>
<programlisting>
function my_sqrt( $num ) {
return $num * $num;
}
echo my_sqrt( 4 ); // outputs '16'.
</programlisting>
</informalexample>
<para>
Multiple values may not be returned, but the same effect can be
achieved by returning a list:
<informalexample>
<programlisting>
function foo() {
return array( 0, 1, 2 );
}
list( $zero, $one, $two ) = foo();
</programlisting>
</informalexample>
</sect2>
<sect2 id="keyword.function.arguments">
<title>Arguments</title>
<simpara>
Information may be passed to functions via the argument list,
which is a comma-delimited list of variables and/or constants.
<para>
PHP3 supports passing arguments by value (the default), <link
linkend="keyword.function.arguments.reference">passing by
reference</link>, and <link
linkend="keyword.function.arguments.default">default argument
values</link>. Variable-length argument lists are not supported,
but a similar effect may be achieved by passing arrays.
<sect3 id="keyword.function.arguments.reference">
<title>Passing by reference</title>
<simpara>
By default, function arguments are passed by value. If you wish
to allow a function to modify its arguments, you may pass them
by reference.
<para>
If you wish a function's argument to always be passed by
reference, you can prepend an ampersand (&) to the argument
name in the function definition:
<informalexample>
<programlisting>
function foo( &$bar ) {
$bar .= ' and something extra.';
}
$str = 'This is a string, ';
foo2( $str );
echo $str; // outputs 'This is a string, and something extra.'
</programlisting>
</informalexample>
<para>
If you wish to pass a variable by reference to a function which
does not do this by default, you may prepend an ampersand to the
argument name in the function call:
<informalexample>
<programlisting>
function foo( $bar ) {
$bar .= ' and something extra.';
}
$str = 'This is a string, ';
foo2( $str );
echo $str; // outputs 'This is a string, '
foo2( &$str );
echo $str; // outputs 'This is a string, and something extra.'
</programlisting>
</informalexample>
</sect3>
<sect3 id="keyword.function.arguments.default">
<title>Default values</title>
<para>
A function may define C++-style default values for scalar
arguments as follows:
<informalexample>
<programlisting>
function makecoffee( $type = "cappucino" ) {
echo "Making a cup of $type.\n";
}
echo makecoffee();
echo makecoffee( "espresso" );
</programlisting>
</informalexample>
<para>
The output from the above snippet is:
<screen>
Making a cup of cappucino.
Making a cup of espresso.
</screen>
<para>
Note that when using default arguments, any defaults should be on
the right side of any non-default arguments; otherwise, things
will not work as expected. Consider the following code snippet:
<informalexample>
<programlisting>
function makeyogurt( $type = "acidophilus", $flavour ) {
return "Making a bowl of $type $flavour.\n";
}
echo makeyogurt( "raspberry" ); // won't work as expected
</programlisting>
</informalexample>
<para>
The output of the above example is:
<screen>
Warning: Missing argument 2 in call to makeyogurt() in /usr/local/etc/httpd/htdocs/php3test/functest.html on line 41
Making a bowl of raspberry .
</screen>
<para>
Now, compare the above with this:
<informalexample>
<programlisting>
function makeyogurt( $flavour, $type = "acidophilus" ) {
return "Making a bowl of $type $flavour.\n";
}
echo makeyogurt( "raspberry" ); // works as expected
</programlisting>
</informalexample>
<para>
The output of this example is:
<screen>
Making a bowl of acidophilus raspberry.
</screen>
</sect3>
</sect2>
</sect1>
<sect1 id="keyword.old-function">
<title>OLD_FUNCTION</title>
<simpara>
The OLD_FUNCTION statement allows you to declare a function using
a syntax identical to PHP/FI2 (except you must replace 'function'
with 'old_function'.
<simpara>
This is a deprecated feature, and should only be used by the
PHP/FI2->PHP3 convertor.
<simpara>
Functions declared as OLD_FUNCTION cannot be called from PHP's
internal code. Among other things, this means you can't use them
in functions such as <function>usort</function>,
<function>array_walk</function>, and
<function>register_shutdown_function</function>. You can get
around this limitation by writing a wrapper function (in normal
PHP3 form) to call the OLD_FUNCTION.
</sect1>
<sect1 id="keyword.class">
<title>CLASS</title>
<para>
A class is a collection of variables and functions working with
these variables. A class is defined using the following syntax:
<informalexample>
<programlisting role=php>
<?php
class Cart {
var $items; // Items in our shopping cart
// Add $num articles of $artnr to the cart
function add_item($artnr, $num) {
$this->items[$artnr] += $num;
}
// Take $num articles of $artnr out of the cart
function remove_item($artnr, $num) {
if ($this->items[$artnr] > $num) {
$this->items[$artnr] -= $num;
return true;
} else {
return false;
}
}
}
?>
</programlisting>
</informalexample>
<para>
This defines a class named Cart that consists of an associative
array of articles in the cart and two functions to add and remove
items from this cart.
</para><para>
Classes are types, that is, they are blueprints for actual
variables. You have to create a variables of the desired type with
the new operator.
</para>
<informalexample>
<programlisting role=php>
$cart = new Cart;
$cart->add_item("10", 1);
</programlisting>
</informalexample>
<para>
This creates an object $cart of the class Cart. The function
add_item() of that object is being called to add 1 item of article
number 10 to the cart.
</para><para>
Classes can be extensions of other classes. The extended or
derived class has all variables and functions of the base class
and what you add in the extended defintion. This is done using
the extends keyword.
</para>
<informalexample>
<programlisting role=php>
class Named_Cart extends Cart {
var $owner;
function set_owner($name) {
$this->owner = $name;
}
}
</programlisting>
</informalexample>
<para>
This defines a class Named_Cart that has all variables and
functions of Cart plus an additional variable $owner and an
additional function set_owner(). You create a named cart the usual
way and can now set and get the carts owner. You can still use
normal cart functions on named carts:
</para>
<informalexample>
<programlisting role=php>
$ncart = new Named_Cart; // Create a named cart
$ncart->set_owner("kris"); // Name that cart
print $ncart->owner; // print the cart owners name
$ncart->add_item("10", 1); // (inherited functionality from cart)
</programlisting>
</informalexample>
<para>
Within functions of a class the variable $this means this
object. You have to use $this->something to access any variable or
function named something within your current object.
</para>
<para>
Constructors are functions in a class that are automatically
called when you create a new instance of a class. A function
becomes a constructur when it has the same name as the class.
</para>
<informalexample>
<programlisting role=php>
class Auto_Cart extends Cart {
function Auto_Cart() {
$this->add_item("10", 1);
}
}
</programlisting>
</informalexample>
<para>
This defines a class Auto_Cart that is a Cart plus a constructor which
initializes the cart with one item of article number "10" each time
a new Auto_Cart is being made with "new". Constructors
can also take arguments and these arguments can be optional, which
makes them much more useful.
</para>
<informalexample>
<programlisting role=php>
class Constructor_Cart {
function Constructor_Cart($item = "10", $num = 1) {
$this->add_item($item, $num);
}
}
// Shop the same old boring stuff.
$default_cart = new Constructor_Cart;
// Shop for real...
$different_cart = new Constructor_Cart("20", 17);
</programlisting>
</informalexample>
</sect1>
<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
sgml-parent-document:nil
sgml-default-dtd-file:"../manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
-->
|