Q:

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

belongs to collection: PHP Classes & Objects Programs

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

PHP Classes & Objects Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
PHP program to demonstrate the default or no-argum... >>
<< PHP program to demonstrate the use of printf() fun...