You have learned some ways to have your main program share variable information with your functions. In addition to parameter passing, sometimes you'll want your functions to have access to variables created in the main program. This is especially true because all the variables automatically created by PHP (such as those coming from forms) will be generated at the main level. You must tell PHP when you want a function to use a variable that has been created at the main level.
TRAP |
If you've programmed in another language, you're bound to get confused by the way PHP handles global variables. In most languages, any variable created at the main level is automatically available to every function. In PHP, you must explicitly request that a variable be global inside a function. If you don't do this, a new local variable with the same name (and no value) will be created at the function level. |
To illustrate the notion of global variables, take a look at the scope demo, shown in Figure 3.14.
Take a look at the code for the Scope Demo, and you'll see how it works.
<html> <head> <title>Scope Demo</title> </head> <body> <h1>Scope Demo</h1> <h3>Demonstrates variable scope</h3> <? $a = "I have a value"; $b = "I have a value"; print <<<HERE outside the function, <br> \$a is "$a", and<br> \$b is "$b"<br><br> HERE; myFunction(); function myFunction(){ //make $a global, but not $b global $a; print <<<HERE inside the function, <br> \$a is "$a", and<br> \$b is "$b"<br><br> HERE; } // end myFunction ?> </body> </html>
For this demonstration, I created two variables, called $a and $b. I gave them both the value "I have a value." As a test, I printed out the values for both $a and $b.
TRICK |
Notice the trick I used to make the actual dollar sign show up in the quotes. When PHP sees a dollar sign inside quotes, it usually expects to be working with a variable. Some-times (as in this case) you really want to print a dollar sign. You can precede a dollar sign with a backslash to indicate you really want the dollar sign to appear. So, print $a will print the value of the variable $a, but print \$a will print out the value "$a". |