Page 189 - Beginning PHP 5.3
P. 189
Chapter 7: Functions
You can see the script ’ s output in Figure 7 - 4 .
Figure 7-4
Notice how the calling code tries to display the values of $hello and $world , but nothing gets
displayed. This is because the $hello and $world variables that were created inside the function don ’ t
exist outside the function. The scope of $hello and $world is said to be limited to the function that
created them; they are said to be local variables .
Now at first glance you might think that this is a drawback, because it means you can ’ t easily access
variables within a function from outside the function. In fact, though, this is a good feature, because it
means that the names of variables used inside a function don ’ t clash with the names of variables used
outside the function.
Consider the following example:
function describeMyDog() {
$color = “brown”;
echo “My dog is $color < br/ > ”;
}
// Define my cat’s color
$color = “black”;
// Display info about my dog and cat
describeMyDog();
echo “My cat is $color < br/ > ”;
Notice that the code creates variables with the same name — $color — both inside and outside the
function. Thanks to the concept of variable scope, however, the $color variable inside the
describeMyDog() function is independent of the $color variable created outside the function, so the
code produces the expected result:
My dog is brown
My cat is black
151
9/21/09 9:00:54 AM
c07.indd 151
c07.indd 151 9/21/09 9:00:54 AM