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

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

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.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.