|
Variables are used for storing data/values for use later in your script. This is a easy way to name and hold on to any value you want for later use. There are a few things you need to know
about variables in PHP. First, all variables in PHP begin with "$", the dollar sign. Unlike C programming your variables do not need to be declared before using them. PHP doesn't really care
what type of data you are assigning to the variable.
Assigning variables:
<? $myAge = 23; // Assign 23 to the variable $myAge $myNumber = 12 + 12; // Assigns 24 to the variable $myNumber ?>
Reassigning variables:
<? $number = 10; // Assign 10 to $number $number = 25; // Set $number to 25 ?>
Checking if a variable is set:
In some cases you may want to see if a variable has been set yet. An example would be that you have a form a user fills out and when they submit it, the code will put the users input into a database. Well, you need to check if the submit button was pressed. You would use the isset function to check this.
<? if (isset($_POST['Submit'])) { echo "The submit button was pressed"; } else { echo "The submit button was not pressed"; } ?>
Variable Scope:
Variable Scope basically means, how far a variables reach is in a script. To make it simple, if you set a variable at the top of the script and then do a bunch of code and exit and enter PHP multiple times in your script. At the end, so long as you have not reassigned the variable then it will still be the same at the end of the script. You can also carry a variable across pages with sessions, databases and cookies. We will be talking about all those in later writings.
If you set a variable inside of a function, then that variable cannot be used outside the function unless you have certain code that allows that. Also a variable outside of the function cannot be used inside of a function unless you have code that allows that to happen. If I confused you there, here is another way of saying it. Inside a function, you do not have access to variables outside of that function. Outside the function you do not have access to the variables inside the function unless your code allows that.
|