|Many beginning PHP programmers are confused as to when a PHP variable is available within a PHP program. Basically it depends on how and where the variable is declared or created. In previous tutorials*, you learned that in most cases you will declare a variable by giving it an initial value.|
That takes care of how to declare a variable but where you declare a variable is also important. A variable is available only where it was created. For example, if we create a variable within a function, that variable is only available within that function. It does not exist outside of that function. Think of the function as a box that contains the variable and you cannot use the variable outside of that box. Let's take a look at an example. The function below creates the variable $dollar_amt and then prints a sentence to the web browser.
There is no problem here because we are using the variable in an echo statement and that echo statement is part of the same function that created the variable. (All of it is within the box.) But if we want to use the variable in a second echo statement later in the program, we will no longer be working inside the box. We will be attempting to use the variable "outside" of the original function that created it.
Because the variable is not available to the second echo statement the webpage will look like this.
You will need to send a check for dollars.
But you can create variables anywhere in your program and not just inside functions. What about a variable declared outside of a function, for example within the main body of your program? The same availability rule is true. The variable is available only where it was created (in this case outside the box). If you attempt to use the variable within a function/box, it will not be available. For example if you set the initial value of the $cent_amt variable to 50 in your program, you cannot use it inside the function below.
In the web browser you will only see the following sentence.
The cost is 10 dollars and cents.
But what about those times when you need to use an "outside" variable in a function? An easy way to solve this problem is to pass that variable as an argument when you call the function.
*You may wish to read some of the previous tutorials about PHP variables and functions.