Getting global variable inside Functions in PHP

Many times we will not get the value of the variables inside a function to use. The reason is that the variables became local inside the function so variables declared outside the function will not be available inside the function for use. Also the variables used inside the function will not be available for the main script to use. For this return statement is to be used.

We can also pass the variables into the function by using arguments. To use the variables of main script inside the function we have to make them global first. Here is the code explaining how variables can be declared inside the function as global.
$v1="Hello 1";
function test(){
echo "The value of \$v1= $v1";
// The above line will print The value of $v1=
global $v1;
echo "<br>The value of \$v1= $v1";
// The above line will print The value of $v1= Hello 1
$v2="Hello 2";

echo "<br>The value of \$v2=$v2";
// The above line will print The value of $v2= 
In above code we have seen the local variable inside the function lost its value once function execution is completed. To retain the values for successive execution of the function we have to use static variables. Here is the code to explain about static variables.
function my_function(){
static $my_static_variable=0;
$my_static_variable=$my_static_variable + 1 ;
$my_local_variable=$my_local_variable + 1 ;
echo "Static varaible :".$my_static_variable;
echo ",Local Variable :".$my_local_variable;

echo "<br>";
Output is here.
Static varaible :1, Local Variable :1
Static varaible :2, Local Variable :1
The data associated with static variable is retained after the execution of the function.

Global Variables

We can declare variables inside or outside the function to make it available throughout the script.
function test(){ 
echo $v3; // Output is 8
We can declare variables as Global outside the function.
function test(){ 
$v1=5; //  local variable 
echo $v1; // Output is 2 ( not 5 ) 
Functions Types of variables in PHP
Subscribe to our YouTube Channel here


* indicates required
Subscribe to plus2net



    How to use the value that returned by the function, in the "if()" statement ?

    Post your comments , suggestion , error , requirements etc here

    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2022 All rights reserved worldwide Privacy Policy Disclaimer