Global Variable
2. Global variables can be accessed from any part of the program except function.
3.To access a global variable from within a function, use the global keyword.
Example: 1
<?phpfunction echo_ip(){
$user_ip=$_SERVER["REMOTE_ADDR"]; // local scope
$str="Your IP address is ".$user_ip;
echo $str;
}echo_ip();?>
Output
Your IP address is ::1 Here $user_ip is declared local.
Example: 2
<?php
$user_ip=$_SERVER["REMOTE_ADDR"]; // global scopefunction echo_ip(){$str="Your IP address is ".$user_ip;
echo $str;
}echo_ip();?>
Output
Here we don't see any output. Because $user_ip is declared global.To access $user_ip global variable from within a function, use the global keyword.
Example: 3
<?php
$user_ip=$_SERVER["REMOTE_ADDR"]; // global scopefunction echo_ip(){
global $user_ip;
$str="Your IP address is ".$user_ip;
echo $str;
}echo_ip();?>
Output
Your IP address is ::1
Example: 4
<?php
$a = 5;$b = 10;
function sum(){
global $a, $b;
$b = $a + $b;
}sum();
echo $b;?>
Output
15