TechniqueUse the session_register() function to register a session variable: <?php session_register('session_variable'); $session_variable = $session_variable ? $session_variable + 1 : 20; echo $session_variable; ?> CommentsIn PHP, there are currently 3 types of variables , all with different scopes and purposes. The first type of variable and the one with the most limited scope is the local variable. A local variable is any variable that is within the scope of a function, and it lasts only for the time of the function. Consider the following: <?php srand((double)microtime() * 1000000); function get_number($num) { $num *= rand(); return ($num); } $number1 = get_number(rand()); $number2 = get_number(5); $number3 = get_number(5); print "Number 1 is $number1\n<br>\n Number 2 is $number2\n<br>\n Number 3 is $number3\n<br>\n"; ?> In this example, the $ret variable is locally scoped; that is, its value is not accessible outside the scope of the get_number() function. The next type of variable is a global variable, which is any variable that is declared outside of a class or function (or declared by the global statement or declared through the $ GLOBALS array). Global variables last for the duration of the script's execution. The last type of variable added in PHP 4 is the session variable. Session variables can (in theory) last forever, unless you or the user explicitly deletes them. (They can be automatically deleted after a certain time by setting configuration options correctly.) So, session variables are simply regular variables that are declared using the session_register() function. They can be of any PHP-supported type: arrays, strings, numbers , even objects. The behavior of session_register() depends on the value of the register_globals PHP configuration parameter. If register_globals is on, session_register('foo') will save a global variable $foo in the session store. If it's off, it will look inside $HTTP_SESSION_VARS[] array, so $HTTP_SESSION_VARS['foo' ] will be saved. Keep these considerations in mind while you read the rest of this chapter. A list of the topics we'll discuss is
|