PHP program to demonstrate the use of the local and global variables

Here, we are going to demonstrate the use of the local and global variables in PHP?
Submitted by Nidhi, on November 18, 2020 [Last updated : March 13, 2023]

Use of Local and Global Variables

Here, we will demonstrate local and global variables with the same name and access the global variable from the scope of the local variable.

Demonstrate the example use of local and global variables in PHP

The source code to demonstrate the local and global variables is given below. The given program is compiled and executed successfully.

<?php
    //PHP program to access the global variable 
    //from the function.
    $NUM=10;
    function test_fun()
    {
        $NUM=20;   
        printf("<br>Local NUM : %d",$NUM);
        
        global $NUM;
        printf("<br>Global NUM : %d",$NUM);
    }
    test_fun();
?> 

Output

Local NUM : 20
Global NUM : 10

Explanation

In the above program, we created a global variable $NUM initialized with value 10. After that we created the local variable $NUM initialized with 20 inside the function test_fun(). And then printed the value of the local variable inside the function test_fun(). After that, we used the global keyword to access the value of the global variable $NUM, and then we printed the value of the global variable on the webpage.

PHP Class & Object Programs »



Related Programs




Comments and Discussions!

Load comments ↻






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