Page 188 - Beginning PHP 5.3
P. 188
Part II: Learning the Language
As a matter of fact, you can use the return statement without including a value to return:
function myFunc() {
// (do stuff here)
return;
}
This simply exits the function at that point, and returns control to the calling code. This is useful if you
simply want a function to stop what it ’ s doing, without necessarily returning a value.
Understanding Variable Scope
You can create and use variables within a function, just as you can outside functions. For example, the
following function creates two string variables, $hello and $world , then concatenates their values and
returns the result:
function helloWithVariables() {
$hello = “Hello, “;
$world = “world!”;
return $hello . $world;
}
echo helloWithVariables(); // Displays “Hello, world!”
However, the important thing to remember is that any variables created within a function are not
accessible outside the function. So in the preceding example, the variables $hello and $world that are
defined inside the function are not available to the calling code. The next example demonstrates this:
< !DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd” >
< html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en” lang=”en” >
< head >
< title > Understanding variable scope < /title >
< link rel=”stylesheet” type=”text/css” href=”common.css” / >
< /head >
< body >
< h1 > Understanding variable scope < /h1 >
< ?php
function helloWithVariables() {
$hello = “Hello, “;
$world = “world!”;
return $hello . $world;
}
echo helloWithVariables() . “ < br/ > ”;
echo “The value of \$hello is: ‘$hello’ < br/ > ”;
echo “The value of \$world is: ‘$world’ < br/ > ”;
? >
< /body >
< /html >
150
9/21/09 9:00:54 AM
c07.indd 150 9/21/09 9:00:54 AM
c07.indd 150