Home >>PHP Object Oriented >PHP Global Variables

PHP Global Variables

Global Variable

=> Global variables are always initialize outside the function body.

=> Global variable work inside the function body as well as outside function body.

=> To access Global variable we have to use global keyword.

<?php
		
$x=100;
		
$y=200;
		
function add()
		
{
			
global $x,$y;
			
$sum=$x+$y;
			
echo "sum of given no=".$sum;
		
}
		
function sub()
		
{
			
global $x,$y;
			
$sub=$x-$y;
			
echo "subtraction of given no=".$sub;
		
}
		
add();
		
sub();

?>

Output Sum of given no = 300 Subtraction of given no = -100

In the above example There are two variables declare $x and $y outside the function body. Now if we want to call these global variable $x and $y inside add( ) and sub( ) function then used "global" keyword before the variable name like "global $x" and "global $y".


No Sidebar ads