My understanding is that session variables are saved in a small file to the server, and it uses a cookie with a session id number to identify it to get the session variables. This all happens automatically behind the scenes. We don't have to do anything except put this code at the very, very top of the page, above all HTML, above absolutely everything: <?php session_start() ?>
Then we create and assign values to the session variables like this:
Think of a session variable like you would any other variable. It has a name (any name except for key words) that you want to give it, and you can then assign a value to it.
The value can be a literal number or string like this:
$_SESSION["myVar"] =15; //the name of the session variable "myVar" can be anything you want
$_SESSION["myVar"] ="Hello World";
Or it can be a value from a different variable like this:
$_SESSION["myVar"] = $num;
$_SESSION["myVar"] = $total; //It doesn't have to be named the same as your session variable, but it can make it easier to keep track of if you do name it the same thing like this--> $_SESSION["myVar"] = $myVar; Just remember that these are two totally different variables.
NOTE: Be sure to use square brackes [ ], not parentheses in the session variable.
So to answer your question, $_SESSION["num1"] and $_SESSION["num2"] are two totally different variables and can hold separate values. However, $num1 and $num2 are just regular variables (not session variables), and they are totally separate variables from $_SESSION["num1"] and $_SESSION["num2"]. They just happen to have the same names but they are not the same.
For example:
$_SESSION["num1"] = 10;
$num1 = 5;
In this case, $_SESSION["num1"] will still = 10 because it is a different variable than $num1.
You must do this: $_SESSION["num1"] = $num1; //Now the session variable will equal 5
It works the same in reverse. If you change the value of the session variable, it will not affect the $num1 variable at all. It will only affect it if you set the value of $num1 to the session variable, like this:
$num1 = 12;
$_SESSION["num1"] = 6;
The value of $num1 has not changed. It is still 12.
$num1 = $_SESSION["num1"]; //Only now did $num1 change it's value to 6.
You can also use different variables with different names to change the values:
$total = 2;
$_SESSION["num1"] = $total;
$num1 = 5;
$total = 20;
What does $_SESSION["num1"] equal at this point? The answer is 2 because that was the value of $total when the value was assigned to the session variable even though $total equals 20 now. The value of $num1 is still 5 and it did not change the session variable value because it is completely unrelated to the session variable $_SESSION["num1"]. They just happen to have the same name.
No comments:
Post a Comment