PHP:Declare global variables
Blogs20122012-09-29
Declare global variable
I had a small bug in the PHP codes which prevents webpage from correctly display: global variable must be declared in functions before using it. The following codes doesnāt work:
$config = array(
'header' => array(...),
);
function foo() {
if (isset($config) && is_array($config['header'])) {
//do some stuff.
}
}
foo();the foo() will not be executed because $config is unseen and not set in the function. To correct it, add:
global $config;
at the beginning of the function, to declare āI have been defined some place elseā, like this:
function foo() {
global $config;
if (isset($config) && is_array($config['header'])) {
//do some stuff.
}
}
foo();Right now it works.
1 more thing is: The $_COOKIE is not secure enough because it can be seen in different scripts as long as it is set. But $_SESSION is much more safe since it can only be seen in the script it is called.
echo "<pre>"; print_r($_COOKIE); print_r($_SESSION); echo "</pre>";$_COOKIE will be printed out here, but $_SESSION not. So for security reason, $_SESSION is more considerable.
