cvs: phpdoc /kr/language control-structures.xml expressions.xml functions.xml oop.xml references.xml

From: Date: Tue, 09 Jan 2001 11:00:02 +0000
Subject: cvs: phpdoc /kr/language control-structures.xml expressions.xml functions.xml oop.xml references.xml
Groups: php.doc 
Request: Send a blank email to phpdoc+get-969333505@lists.php.net to get a copy of this message
bibi Tue Jan 9 03:00:02 2001 EDT Added files: /phpdoc/kr/language expressions.xml functions.xml oop.xml references.xml control-structures.xml Log: Added original English version

Index: phpdoc/kr/language/expressions.xml +++ phpdoc/kr/language/expressions.xml <chapter id="language.expressions"> <title>Expressions</title> <simpara> Expressions are the most important building stones of PHP. In PHP, almost anything you write is an expression. The simplest yet most accurate way to define an expression is "anything that has a value".</simpara> <simpara> The most basic forms of expressions 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> <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.</simpara> <para> Slightly more complex examples for expressions are functions. For instance, consider the following function: <informalexample> <programlisting> function foo () { return 5; } </programlisting> </informalexample></para> <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> <simpara> Of course, values in PHP don't have to be integers, and very often they aren't. PHP supports three 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> <simpara> So far, users of PHP/FI 2 shouldn't feel any change. However, PHP takes expressions much further, in the same way many other languages do. PHP 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> <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 enhances the increment/decrement capabilities by making these expressions as well, like in C. In PHP, 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> <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 &gt; (bigger than), &gt;= (bigger than or equal to), == (equal), != (not equal), &lt; (smaller than) and &lt;= (smaller than or equal to). These expressions are most commonly used inside conditional execution, such as <literal>if</literal> statements.</simpara> <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, 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.</simpara> <para> There is one more expression that may seem odd if you haven't seen it in other languages, the ternary conditional operator: <informalexample><programlisting> $first ? $second : $third </programlisting></informalexample> If the value of the first subexpression is true (non-zero), then it the second subexpression is evaluated, and that is the result of the conditional expression. Otherwise, the third subexpression is evaluated, and that is the value.</para> <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 $g */ $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></para> <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> <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> <simpara> PHP 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 <replaceable>expr</replaceable> to indicate any valid PHP expression.</simpara> </chapter> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t sgml-parent-document:nil sgml-default-dtd-file:"../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: --> Index: phpdoc/kr/language/functions.xml +++ phpdoc/kr/language/functions.xml <chapter id="functions"> <title>Functions</title> <sect1 id="functions.user-defined"> <title>User-defined functions</title> <para> A function may be defined using syntax such as the following: <informalexample> <programlisting role="php"> function foo ($arg_1, $arg_2, ..., $arg_n) { echo "Example function.\n"; return $retval; } </programlisting> </informalexample> </para> <simpara> Any valid PHP code may appear inside a function, even other functions and <link linkend="keyword.class">class</link> definitions. </simpara> <simpara> In PHP 3, functions must be defined before they are referenced. No such requirement exists in PHP 4. </simpara> <simpara> PHP does not support function overloading, nor is it possible to undefine or redefine previously-declared functions. </simpara> <simpara> PHP 3 does not support variable numbers of arguments to functions, although default arguments are supported (see <link linkend="functions.arguments.default">Default argument values</link> for more information). PHP 4 supports both: see <link linkend="functions.variable-arg-list">Variable-length argument lists</link> and the function references for <function>func_num_args</function>, <function>func_get_arg</function>, and <function>func_get_args</function> for more information. </simpara> </sect1> <sect1 id="functions.arguments"> <title>Function arguments</title> <simpara> Information may be passed to functions via the argument list, which is a comma-delimited list of variables and/or constants. </simpara> <para> PHP supports passing arguments by value (the default), <link linkend="functions.arguments.by-reference">passing by reference</link>, and <link linkend="functions.arguments.default">default argument values</link>. Variable-length argument lists are supported only in PHP 4 and later; see <link linkend="functions.variable-arg-list">Variable-length argument lists</link> and the function references for <function>func_num_args</function>, <function>func_get_arg</function>, and <function>func_get_args</function> for more information. A similar effect can be achieved in PHP 3 by passing an array of arguments to a function: <informalexample> <programlisting role="php"> function takes_array($input) { echo "$input[0] + $input[1] = ", $input[0]+$input[1]; } </programlisting> </informalexample> </para> <sect2 id="functions.arguments.by-reference"> <title>Making arguments be passed by reference</title> <simpara> By default, function arguments are passed by value (so that if you change the value of the argument within the function, it does not get changed outside of the function). If you wish to allow a function to modify its arguments, you must pass them by reference. </simpara> <para> If you want an argument to a function to always be passed by reference, you can prepend an ampersand (&amp;) to the argument name in the function definition: <informalexample> <programlisting role="php"> function add_some_extra(&amp;$string) { $string .= 'and something extra.'; } $str = 'This is a string, '; add_some_extra($str); echo $str; // outputs 'This is a string, and something extra.' </programlisting> </informalexample> </para> <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 role="php"> function foo ($bar) { $bar .= ' and something extra.'; } $str = 'This is a string, '; foo ($str); echo $str; // outputs 'This is a string, ' foo (&amp;$str); echo $str; // outputs 'This is a string, and something extra.' </programlisting> </informalexample> </para> </sect2> <sect2 id="functions.arguments.default"> <title>Default argument values</title> <para> A function may define C++-style default values for scalar arguments as follows: <informalexample> <programlisting role="php"> function makecoffee ($type = "cappucino") { return "Making a cup of $type.\n"; } echo makecoffee (); echo makecoffee ("espresso"); </programlisting> </informalexample> </para> <para> The output from the above snippet is: <screen> Making a cup of cappucino. Making a cup of espresso. </screen> </para> <simpara> The default value must be a constant expression, not (for example) a variable or class member. </simpara> <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 role="php"> function makeyogurt ($type = "acidophilus", $flavour) { return "Making a bowl of $type $flavour.\n"; } echo makeyogurt ("raspberry"); // won't work as expected </programlisting> </informalexample> </para> <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> <para> Now, compare the above with this: <informalexample> <programlisting role="php"> function makeyogurt ($flavour, $type = "acidophilus") { return "Making a bowl of $type $flavour.\n"; } echo makeyogurt ("raspberry"); // works as expected </programlisting> </informalexample> </para> <para> The output of this example is: <screen> Making a bowl of acidophilus raspberry. </screen> </para> </sect2> <sect2 id="functions.variable-arg-list"> <title>Variable-length argument lists</title> <simpara> PHP 4 has support for variable-length argument lists in user-defined functions. This is really quite easy, using the <function>func_num_args</function>, <function>func_get_arg</function>, and <function>func_get_args</function> functions. </simpara> <simpara> No special syntax is required, and argument lists may still be explicitly provided with function definitions and will behave as normal. </simpara> </sect2> </sect1> <sect1 id="functions.returning-values"> <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 role="php"> function square ($num) { return $num * $num; } echo square (4); // outputs '16'. </programlisting> </informalexample> </para> <para> You can't return multiple values from a function, but similar results can be obtained by returning a list. <informalexample> <programlisting role="php"> function small_numbers() { return array (0, 1, 2); } list ($zero, $one, $two) = small_numbers(); </programlisting> </informalexample> </para> <para> To return a reference from a function, you have to use the reference operator &amp; in both the function declaration and when assigning the returned value to a variable: <informalexample> <programlisting role="php"> function &amp;returns_reference() { return $someref; } $newref =&amp;returns_reference(); </programlisting> </informalexample> </para> </sect1> <sect1 id="functions.old-syntax"> <title><literal>old_function</literal></title> <simpara> The <literal>old_function</literal> statement allows you to declare a function using a syntax identical to PHP/FI2 (except you must replace 'function' with 'old_function'. </simpara> <simpara> This is a deprecated feature, and should only be used by the PHP/FI2->PHP 3 convertor. </simpara> <warning> <para> Functions declared as <literal>old_function</literal> 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 PHP 3 form) to call the <literal>old_function</literal>. </para> </warning> </sect1> <sect1 id="functions.variable-functions"> <title>Variable functions</title> <para> PHP supports the concept of variable functions. This means that if a variable name has parentheses appended to it, PHP will look for a function with the same name as whatever the variable evaluates to, and will attempt to execute it. Among other things, this can be used to implement callbacks, function tables, and so forth. </para> <para> <example> <title>Variable function example</title> <programlisting role="php"> &lt;?php function foo() { echo "In foo()&lt;br>\n"; } function bar( $arg = '' ) { echo "In bar(); argument was '$arg'.&lt;br>\n"; } $func = 'foo'; $func(); $func = 'bar'; $func( 'test' ); ?> </programlisting> </example> </para> </sect1> </chapter> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t sgml-parent-document:nil sgml-default-dtd-file:"../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: --> Index: phpdoc/kr/language/oop.xml +++ phpdoc/kr/language/oop.xml <chapter id="language.oop"> <title>Classes and Objects</title> <sect1 id="keyword.class"> <title><literal>class</literal></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"> &lt;?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> <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> <note><simpara> In PHP 4, only constant initializers for <literal>var</literal> variables are allowed. Use constructors for non-constant initializers. </simpara></note> <para> Classes are types, that is, they are blueprints for actual variables. You have to create a variable 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 definition. This is done using the extends keyword. Multiple inheritance is not supported. </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 constructor 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 extends 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> <caution> <simpara> For derived classes, the constructor of the parent class is not automatically called when the derived class's constructor is called. </simpara> </caution> </sect1> </chapter> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t sgml-parent-document:nil sgml-default-dtd-file:"../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: --> Index: phpdoc/kr/language/references.xml +++ phpdoc/kr/language/references.xml <chapter id="language.references"> <title>References Explained</title> <sect1 id="language.references.whatare"> <title>What References Are</title> <simpara> References are a means in PHP to access the same variable content by different names. They are not like C pointers, they are symbol table aliases. Note that in PHP, variable name and variable content are different, so the same content can have different names. The most close analogy is with Unix filenames and files - variable names are directory entries, while variable contents is the file itself. References can be thought of as hardlinking in Unix filesystem. </simpara> </sect1> <sect1 id="language.references.whatdo"> <title>What References Do</title> <para> PHP references allow you to make two variables to refer to the same content. Meaning, when you do: <informalexample> <programlisting role="php"> $a =&amp; $b </programlisting> </informalexample> it means that <varname>$a</varname> and <varname>$b</varname> point to the same variable. <note> <para> <varname>$a</varname> and <varname>$b</varname> are completely equal here, that's not <varname>$a</varname> is pointing to <varname>$b</varname> or vice versa, that's <varname>$a</varname> and <varname>$b</varname> pointing to the same place. </para> </note> </para> <para> The same syntax can be used with functions, that return references, and with <literal>new</literal> operator (in PHP 4.0.4 and later): <informalexample> <programlisting role="php"> $bar =&amp; new fooclass(); $foo =&amp; find_var ($bar); </programlisting> </informalexample> </para> <note> <para> Unless you use the syntax above, the result of <literal>$bar = new fooclass()</literal> will not be the same variable as <literal>$this</literal> in the constructor, meaning that if you have used reference to <literal>$this</literal> in the constructor, you should use reference assignment, or you get two different objects. </para> </note> <para> The second thing references do is to pass variables by-reference. This is done by making a local variable in a function and a variable in the calling scope reference to the same content. Example: <informalexample> <programlisting role="php"> function foo (&amp;$var) { $var++; } $a=5; foo ($a); </programlisting> </informalexample> will make <varname>$a</varname> to be 6. This happens because in the function <varname>foo</varname> the variable <varname>$var</varname> refers to the same content as <varname>$a</varname>. See also more detailed explanations about <link linkend="language.references.pass">passing by reference</link>. </para> <simpara> The third thing reference can do is <link linkend="language.references.return">return by reference</link>. </simpara> </sect1> <sect1 id="language.references.arent"> <title>What References Are Not</title> <para> As said before, references aren't pointers. That means, the following construct won't do what you expect: <informalexample> <programlisting role="php"> function foo (&amp;$var) { $var =&amp; $GLOBALS["baz"]; } foo($bar); </programlisting> </informalexample> </para> <simpara> What happens is that <varname>$var</varname> in foo will be bound with <varname>$bar</varname> in caller, but then it will be re-bound with <varname>$GLOBALS["baz"]</varname>. There's no way to bind <varname>$bar</varname> in the calling scope to something else using the reference mechanism, since <varname>$bar</varname> is not available in the function foo (it is represented by <varname>$var</varname>, but <varname>$var</varname> has only variable contents and not name-to-value binding in the calling symbol table). </simpara> </sect1> <sect1 id="language.references.pass"> <title>Passing by Reference</title> <para> You can pass variable to function by reference, so that function could modify its arguments. The sytax is as follows: <informalexample> <programlisting role="php"> function foo (&amp;$var) { $var++; } $a=5; foo ($a); // $a is 6 here </programlisting> </informalexample> Note that there's no reference sign on function call - only on function definition. Function definition alone is enough to correctly pass the argument by reference. </para> <para> Following things can be passed by reference: <itemizedlist> <listitem> <simpara> Variable, i.e. <literal>foo($a)</literal> </simpara> </listitem> <listitem> <simpara> New statement, i.e. <literal>foo(new foobar())</literal> </simpara> </listitem> <listitem> <para> Reference, returned from a function, i.e.: <informalexample> <programlisting role="php"> function &amp;bar() { $a = 5; return $a; } foo(bar()); </programlisting> </informalexample> See also explanations about <link linkend="language.references.return">returning by reference</link>. </para> </listitem> </itemizedlist> </para> <para> Any other expression should not be passed by reference, as the result is undefined. For example, the following examples of passing by reference are invalid: <informalexample> <programlisting role="php"> function bar() // Note the missing &amp; { $a = 5; return $a; } foo(bar)); foo($a = 5) // Expression, not variable foo(5) // Constant, not variable </programlisting> </informalexample> These requirements are for PHP 4.0.4 and later. </para> </sect1> <sect1 id="language.references.return"> <title>Returning References</title> <para> Returning by-reference is useful when you want to use a function to find which variable a reference should be bound to. When returning references, use this syntax: <informalexample> <programlisting role="php"> function &amp;find_var ($param) { ...code... return $found_var; } $foo =&amp; find_var ($bar); $foo->x = 2; </programlisting> </informalexample> In this example, the property of the object returned by the <varname>find_var</varname> function would be set, not the copy, as it would be without using reference syntax. </para> <note> <simpara> Unlike parameter passing, here you have to use <literal>&amp;</literal> in both places - to indicate that you return by-reference, not a copy as usual, and to indicate that reference binding, rather than usual assignment, should be done for <varname>$foo</varname>. </simpara> </note> </sect1> <sect1 id="language.references.unset"> <title>Unsetting References</title> <para> When you unset the reference, you just break the binding between variable name and variable content. This does not mean that variable content will be destroyed. For example: <informalexample> <programlisting role="php"> $a = 1; $b =&amp; $a; unset ($a); </programlisting> </informalexample> won't unset <varname>$b</varname>, just <varname>$a</varname>. </para> <simpara> Again, it might be useful to think about this as analogous to Unix <command>unlink</command> call. </simpara> </sect1> <sect1 id="language.references.spot"> <title>Spotting References</title> <simpara> Many syntax constructs in PHP are implemented via referencing mechanisms, so everything told above about reference binding also apply to these constructs. Some constructs, like passing and returning by-reference, are mentioned above. Other constructs that use references are: </simpara> <sect2 id="references.global"> <title><literal>global</literal> References</title> <para> When you declare variable as <command>global $var</command> you are in fact creating reference to a global variable. That means, this is the same as: <informalexample> <programlisting role="php"> $var =&amp; $GLOBALS["var"]; </programlisting> </informalexample> </para> <simpara> That means, for example, that unsetting <varname>$var</varname> won't unset global variable. </simpara> </sect2> <sect2 id="references.this"> <title><literal>$this</literal></title> <simpara> In an object method, <varname>$this</varname> is always reference to the caller object. </simpara> </sect2> </sect1> </chapter> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t sgml-parent-document:nil sgml-default-dtd-file:"../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: --> Index: phpdoc/kr/language/control-structures.xml +++ phpdoc/kr/language/control-structures.xml <chapter id="control-structures"> <title>Control Structures</title> <simpara> Any PHP 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="control-structures.if"> <title><literal>if</literal></title> <para> The <literal>if</literal> construct is one of the most important features of many languages, PHP included. It allows for conditional execution of code fragments. PHP features an <literal>if</literal> structure that is similar to that of C: <informalexample> <programlisting> if (expr) statement </programlisting> </informalexample> </para> <simpara> As described in the section about expressions, expr is evaluated to its truth value. If <replaceable>expr</replaceable> evaluates to <literal>TRUE</literal>, PHP will execute statement, and if it evaluates to <literal>FALSE</literal> - it'll ignore it. </simpara> <para> The following example would display <computeroutput>a is bigger than b</computeroutput> if <replaceable>$a</replaceable> is bigger than <replaceable>$b</replaceable>: <informalexample> <programlisting role="php"> if ($a > $b) print "a is bigger than b"; </programlisting> </informalexample> </para> <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 <literal>if</literal> clause. Instead, you can group several statements into a statement group. For example, this code would display <computeroutput>a is bigger than b</computeroutput> if <replaceable>$a</replaceable> is bigger than <replaceable>$b</replaceable>, and would then assign the value of <replaceable>$a</replaceable> into <replaceable>$b</replaceable>: <informalexample> <programlisting role="php"> if ($a > $b) { print "a is bigger than b"; $b = $a; } </programlisting> </informalexample> </para> <simpara> If statements can be nested indefinitely within other <literal>if</literal> statements, which provides you with complete flexibility for conditional execution of the various parts of your program. </simpara> </sect1> <sect1 id="control-structures.else"> <title><literal>else</literal></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 <literal>else</literal> is for. <literal>else</literal> extends an <literal>if</literal> statement to execute a statement in case the expression in the <literal>if</literal> statement evaluates to <literal>FALSE</literal>. For example, the following code would display <computeroutput>a is bigger than b</computeroutput> if <replaceable>$a</replaceable> is bigger than <replaceable>$b</replaceable>, and <computeroutput>a is NOT bigger than b</computeroutput> otherwise: <informalexample> <programlisting role="php"> if ($a > $b) { print "a is bigger than b"; } else { print "a is NOT bigger than b"; } </programlisting> </informalexample> The <literal>else</literal> statement is only executed if the <literal>if</literal> expression evaluated to <literal>FALSE</literal>, and if there were any <literal>elseif</literal> expressions - only if they evaluated to <literal>FALSE</literal> as well (see <link linkend="control-structures.elseif">elseif</link>). </para> </sect1> <sect1 id="control-structures.elseif"> <title><literal>elseif</literal></title> <para> <literal>elseif</literal>, as its name suggests, is a combination of <literal>if</literal> and <literal>else</literal>. Like <literal>else</literal>, it extends an <literal>if</literal> statement to execute a different statement in case the original <literal>if</literal> expression evaluates to <literal>FALSE</literal>. However, unlike <literal>else</literal>, it will execute that alternative expression only if the <literal>elseif</literal> conditional expression evaluates to <literal>TRUE</literal>. For example, the following code would display <computeroutput>a is bigger than b</computeroutput>, <computeroutput>a equal to b</computeroutput> or <computeroutput>a is smaller than b</computeroutput>: <informalexample> <programlisting role="php"> 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> </para> <simpara> There may be several <literal>elseif</literal>s within the same <literal>if</literal> statement. The first <literal>elseif</literal> expression (if any) that evaluates to <literal>true</literal> would be executed. In PHP, 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> <simpara> The <literal>elseif</literal> statement is only executed if the preceding <literal>if</literal> expression and any preceding <literal>elseif</literal> expressions evaluated to <literal>FALSE</literal>, and the current <literal>elseif</literal> expression evaluated to <literal>TRUE</literal>. </simpara> </sect1> <sect1 id="control-structures.alternative-syntax"> <title>Alternative syntax for control structures</title> <para> PHP offers an alternative syntax for some of its control structures; namely, <literal>if</literal>, <literal>while</literal>, <literal>for</literal>, <literal>foreach</literal>, and <literal>switch</literal>. In each case, the basic form of the alternate syntax is to change the opening brace to a colon (:) and the closing brace to <literal>endif;</literal>, <literal>endwhile;</literal>, <literal>endfor;</literal>, <literal>endforeach;</literal>, or <literal>endswitch;</literal>, respectively. <informalexample> <programlisting role="php"> &lt;?php if ($a == 5): ?&gt; A is equal to 5 &lt;?php endif; ?&gt; </programlisting> </informalexample> </para> <simpara> In the above example, the HTML block "A = 5" is nested within an <literal>if</literal> statement written in the alternative syntax. The HTML block would be displayed only if $a is equal to 5. </simpara> <para> The alternative syntax applies to <literal>else</literal> and <literal>elseif</literal> as well. The following is an <literal>if</literal> structure with <literal>elseif</literal> and <literal>else</literal> in the alternative format: <informalexample> <programlisting role="php"> 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> </para> <para> See also <link linkend="control-structures.while">while</link>, <link linkend="control-structures.for">for</link>, and <link linkend="control-structures.if">if</link> for further examples. </para> </sect1> <sect1 id="control-structures.while"> <title><literal>while</literal></title> <para> <literal>while</literal> loops are the simplest type of loop in PHP. They behave just like their C counterparts. The basic form of a <literal>while</literal> statement is: <informalexample> <programlisting> while (expr) statement </programlisting> </informalexample> </para> <simpara> The meaning of a <literal>while</literal> statement is simple. It tells PHP to execute the nested statement(s) repeatedly, as long as the <literal>while</literal> expression evaluates to <literal>TRUE</literal>. 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 <literal>while</literal> expression evaluates to <literal>FALSE</literal> from the very beginning, the nested statement(s) won't even be run once. </simpara> <para> Like with the <literal>if</literal> statement, you can group multiple statements within the same <literal>while</literal> 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> <para> The following examples are identical, and both print numbers from 1 to 10: <informalexample> <programlisting> /* example 1 */ $i = 1; while ($i &lt;= 10) { print $i++; /* the printed value would be $i before the increment (post-increment) */ } /* example 2 */ $i = 1; while ($i &lt;= 10): print $i; $i++; endwhile; </programlisting> </informalexample> </para> </sect1> <sect1 id="control-structures.do.while"> <title><literal>do..while</literal></title> <simpara> <literal>do..while</literal> loops are very similar to <literal>while</literal> loops, except the truth expression is checked at the end of each iteration instead of in the beginning. The main difference from regular <literal>while</literal> loops is that the first iteration of a <literal>do..while</literal> 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 <literal>while</literal> loop (the truth expression is checked at the beginning of each iteration, if it evaluates to <literal>FALSE</literal> right from the beginning, the loop execution would end immediately). </simpara> <para> There is just one syntax for <literal>do..while</literal> loops: <informalexample> <programlisting role="php"> $i = 0; do { print $i; } while ($i>0); </programlisting> </informalexample> </para> <simpara> The above loop would run one time exactly, since after the first iteration, when truth expression is checked, it evaluates to <literal>FALSE</literal> ($i is not bigger than 0) and the loop execution ends. </simpara> <para> Advanced C users may be familiar with a different usage of the <literal>do..while</literal> loop, to allow stopping execution in the middle of code blocks, by encapsulating them with <literal>do..while</literal>(0), and using the <link linkend="control-structures.break"><literal>break</literal></link> statement. The following code fragment demonstrates this: <informalexample> <programlisting role="php"> do { if ($i &lt; 5) { print "i is not big enough"; break; } $i *= $factor; if ($i &lt; $minimum_limit) { break; } print "i is ok"; ...process i... } while(0); </programlisting> </informalexample> </para> <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'. </simpara> </sect1> <sect1 id="control-structures.for"> <title><literal>for</literal></title> <para> <literal>for</literal> loops are the most complex loops in PHP. They behave like their C counterparts. The syntax of a <literal>for</literal> loop is: <informalexample> <programlisting> for (expr1; expr2; expr3) statement </programlisting> </informalexample> </para> <simpara> The first expression (<replaceable>expr1</replaceable>) is evaluated (executed) once unconditionally at the beginning of the loop. </simpara> <simpara> In the beginning of each iteration, <replaceable>expr2</replaceable> is evaluated. If it evaluates to <literal>TRUE</literal>, the loop continues and the nested statement(s) are executed. If it evaluates to <literal>FALSE</literal>, the execution of the loop ends. </simpara> <simpara> At the end of each iteration, <replaceable>expr3</replaceable> is evaluated (executed). </simpara> <simpara> Each of the expressions can be empty. <replaceable>expr2</replaceable> being empty means the loop should be run indefinitely (PHP implicitly considers it as <literal>TRUE</literal>, like C). This may not be as useless as you might think, since often you'd want to end the loop using a conditional <link linkend="control-structures.break"><literal>break</literal></link> statement instead of using the <literal>for</literal> truth expression. </simpara> <para> Consider the following examples. All of them display numbers from 1 to 10: <informalexample> <programlisting role="php"> /* example 1 */ for ($i = 1; $i &lt;= 10; $i++) { print $i; } /* example 2 */ for ($i = 1;;$i++) { if ($i &gt; 10) { break; } print $i; } /* example 3 */ $i = 1; for (;;) { if ($i &gt; 10) { break; } print $i; $i++; } /* example 4 */ for ($i = 1; $i &lt;= 10; print $i, $i++) ; </programlisting> </informalexample> </para> <simpara> Of course, the first example appears to be the nicest one (or perhaps the fourth), but you may find that being able to use empty expressions in <literal>for</literal> loops comes in handy in many occasions. </simpara> <para> PHP also supports the alternate "colon syntax" for <literal>for</literal> loops. <informalexample> <programlisting> for (expr1; expr2; expr3): statement; ...; endfor; </programlisting> </informalexample> </para> <para> Other languages have a <literal>foreach</literal> statement to traverse an array or hash. PHP 3 has no such construct; PHP 4 does (see <link linkend="control-structures.foreach">foreach</link>). In PHP 3, you can combine <link linkend="control-structures.while">while</link> with the <function>list</function> and <function>each</function> functions to achieve the same effect. See the documentation for these functions for an example. </para> </sect1> <sect1 id="control-structures.foreach"> <title><literal>foreach</literal></title> <para> PHP 4 (not PHP 3) includes a <literal>foreach</literal> construct, much like perl and some other languages. This simply gives an easy way to iterate over arrays. There are two syntaxes; the second is a minor but useful extension of the first: <informalexample> <programlisting> foreach(array_expression as $value) statement foreach(array_expression as $key => $value) statement </programlisting> </informalexample> </para> <simpara> The first form loops over the array given by <literal>array_expression</literal>. On each loop, the value of the current element is assigned to <literal>$value</literal> and the internal array pointer is advanced by one (so on the next loop, you'll be looking at the next element). </simpara> <simpara> The second form does the same thing, except that the current element's key will be assigned to the variable <literal>$key</literal> on each loop. </simpara> <para> <note> <para> When <literal>foreach</literal> first starts executing, the internal array pointer is automatically reset to the first element of the array. This means that you do not need to call <function>reset</function> before a <literal>foreach</literal> loop. </para> </note> </para> <para> <note> <para> Also note that <literal>foreach</literal> operates on a copy of the specified array, not the array itself, therefore the array pointer is not modified like with the each construct. </para> </note> </para> <para> You may have noticed that the following are functionally identical: <informalexample> <programlisting role="php"> reset ($arr); while (list(, $value) = each ($arr)) { echo "Value: $value&lt;br&gt;\n"; } foreach ($arr as $value) { echo "Value: $value&lt;br&gt;\n"; } </programlisting> </informalexample> The following are also functionally identical: <informalexample> <programlisting role="php"> reset ($arr); while (list($key, $value) = each ($arr)) { echo "Key: $key; Value: $value&lt;br&gt;\n"; } foreach ($arr as $key => $value) { echo "Key: $key; Value: $value&lt;br&gt;\n"; } </programlisting> </informalexample> </para> <para> Some more examples to demonstrate usages: <informalexample> <programlisting role="php"> /* foreach example 1: value only */ $a = array (1, 2, 3, 17); foreach ($a as $v) { print "Current value of \$a: $v.\n"; } /* foreach example 2: value (with key printed for illustration) */ $a = array (1, 2, 3, 17); $i = 0; /* for illustrative purposes only */ foreach($a as $v) { print "\$a[$i] => $k.\n"; } /* foreach example 3: key and value */ $a = array ( "one" => 1, "two" => 2, "three" => 3, "seventeen" => 17 ); foreach($a as $k => $v) { print "\$a[$k] => $v.\n"; } </programlisting> </informalexample> </para> </sect1> <sect1 id="control-structures.break"> <title><literal>break</literal></title> <simpara> <literal>break</literal> ends execution of the current <literal>for</literal>, <literal>while</literal>, or <literal>switch</literal> structure. </simpara> <simpara> <literal>break</literal> accepts an optional numeric argument which tells it how many nested enclosing structures are to be broken out of. </simpara> <para> <informalexample> <programlisting role="php"> $arr = array ('one', 'two', 'three', 'four', 'stop', 'five'); while (list (, $val) = each ($arr)) { if ($val == 'stop') { break; /* You could also write 'break 1;' here. */ } echo "$val&lt;br&gt;\n"; } /* Using the optional argument. */ $i = 0; while (++$i) { switch ($i) { case 5: echo "At 5&lt;br&gt;\n"; break 1; /* Exit only the switch. */ case 10: echo "At 10; quitting&lt;br&gt;\n"; break 2; /* Exit the switch and the while. */ default: break; } } </programlisting> </informalexample> </para> </sect1> <sect1 id="control-structures.continue"> <title><literal>continue</literal></title> <simpara> <literal>continue</literal> is used within looping structures to skip the rest of the current loop iteration and continue execution at the beginning of the next iteration. </simpara> <simpara> <literal>continue</literal> accepts an optional numeric argument which tells it how many levels of enclosing loops it should skip to the end of. </simpara> <para> <informalexample> <programlisting role="php"> while (list ($key, $value) = each ($arr)) { if (!($key % 2)) { // skip odd members continue; } do_something_odd ($value); } $i = 0; while ($i++ &lt; 5) { echo "Outer&lt;br&gt;\n"; while (1) { echo "&nbsp;&nbsp;Middle&lt;br&gt;\n"; while (1) { echo "&nbsp;&nbsp;Inner&lt;br&gt;\n"; continue 3; } echo "This never gets output.&lt;br&gt;\n"; } echo "Neither does this.&lt;br&gt;\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&amp;vartwo=2"); /* Won't work; looks for a file named 'file.php?varone=1&amp;vartwo=2' * on the local filesystem. */ require ("file.php?varone=1&amp;vartwo=2"); /* Works. */ require ("http://someserver/file.php?varone=1&amp;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 &lt; 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"> &lt;?php echo "Before the return &lt;br&gt;\n"; if (1) { return 27; } echo "After the return &lt;br&gt;\n"; ?&gt; </programlisting> </para> <para> Assume that the main file (<filename>main.html</filename>) contains the following: <programlisting role="php"> &lt;?php $retval = include ('test.inc'); echo "File returned: '$retval'&lt;br&gt;\n"; ?&gt; </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"> &lt;?php include ('test.inc'); echo "Back in main.html&lt;br&gt;\n"; ?&gt; </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&amp;vartwo=2"); /* Won't work; looks for a file named 'file.php?varone=1&amp;vartwo=2' * on the local filesystem. */ include ("file.php?varone=1&amp;vartwo=2"); /* Works. */ include ("http://someserver/file.php?varone=1&amp;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"> &lt;?php define(PHPVERSION, floor(phpversion())); echo "GLOBALS ARE NICE\n"; function goodTea() { return "Oolong tea tastes good!"; } ?&gt; </programlisting> </example> <example> <title>foolib.inc</title> <programlisting role="php"> &lt;?php require ("utils.inc"); function showVar($var) { if (PHPVERSION == 4) { print_r($var); } else { var_dump($var); } } // bunch of other functions ... ?&gt; </programlisting> </example> And then you write a script <literal>cause_error_require.php</literal> <example> <title>cause_error_require.php</title> <programlisting role="php"> &lt;?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); ?&gt; </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] =&gt; 1 [1] =&gt; Array ( [0] =&gt; complex [1] =&gt; 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 sgml-parent-document:nil sgml-default-dtd-file:"../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: -->
« previous php.doc (#969333505) next »