PHP program to demonstrate the use of $GLOBALS to access global variables

Here, we are going to demonstrate the use of $GLOBALS to access global variables in PHP.
Submitted by Nidhi, on November 24, 2020 [Last updated : March 14, 2023]

PHP $GLOBALS Example

Here, we will create a global variable and access the global variable using $GLOBALS.

PHP code to access global variables using $GLOBALS

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.

More PHP Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.