Variables declared as global within a function would be able to the access the global variable defined by the same name. If not defined using global then the function will encounter 'Undefined variable' error.
<?php
global $blog_id;
$blog_id = "phpCookbook";
function access_constant() {
echo "access_constant: before assign, \$blog_id=". $blog_id . "<br/>";
$blog_id = "access_constant";
echo "access_constant: after assign, \$blog_id=". $blog_id . "<br/>";
}
function initialize_constant() {
global $blog_id;
$blog_id = "initialize_constant";
echo "initialize_constant: after assign, \$blog_id=". $blog_id . "<br/>";
}
echo "before access_constant: " . $blog_id . "<br/>";
access_constant();
echo "after access_constant: " . $blog_id . "<br/>";
echo "before initialize_constant: " . $blog_id . "<br/>";
initialize_constant();
echo "after initialize_constant: " . $blog_id . "<br/>";
?>
Output:
before access_constant: phpCookbook
Notice: Undefined variable: blog_id in C:\phpProjects\examples\global.php on line 5
access_constant: before assign, $blog_id=
access_constant: after assign, $blog_id=access_constant
after access_constant: phpCookbook
before initialize_constant: phpCookbook
initialize_constant: after assign, $blog_id=initialize_constant
after initialize_constant: initialize_constant
Another example
<?php
$x= "This is X";
$y = "This is Y";
print $x."\n";
printGlobal();
function printGlobal() {
global $x;
global $y;
print "Within print global\n";
print $GLOBALS["x"]."\n";
print $y."\n";
}
function callHeader() {
global $request;
if (!isset($request['header'])) {
$request['header'] = 0;
} else {
++$request['header'];
}
print $request['header'] . "\n";
}
callHeader();
callHeader();
print $GLOBALS['request']['header'] . "\n";
global $request;
print $request['header'];
?>
Output:
This is X
Within print global
This is X
This is Y
0
1
1
1