The source code to demonstrate the use of $GLOBALS to access global variables is given below. The given program is compiled and executed successfully.
<?php
//PHP program to demonstrate the use of
//$GLOBALS to access global variables.
$num = 30;
function sumNumber()
{
$num = 20;
$res = 0;
$res = $GLOBALS['num'] + $num;
return $res;
}
printf("Sum is: %d<br>", sumNumber());
?>
Output:
Sum is: 50
Explanation:
In the above program, we created a global variable $num, and then we created a function sumNumber() to calculate the sum of numbers. We also created a local variable with the name $num inside the sumNumber() function, and then we accessed the global variable using $GLOBALS and then return the sum of local and global variables that will be printed on the webpage.
Program/Source Code:
The source code to demonstrate the use of $GLOBALS to access global variables is given below. The given program is compiled and executed successfully.
Output:
Explanation:
In the above program, we created a global variable $num, and then we created a function sumNumber() to calculate the sum of numbers. We also created a local variable with the name $num inside the sumNumber() function, and then we accessed the global variable using $GLOBALS and then return the sum of local and global variables that will be printed on the webpage.
need an explanation for this answer? contact us directly to get an explanation for this answer