Example: Program in Php to show the concept of Global variables using php function.
<!DOCTYPE html>
<html>
<body>
<?php
$x = 500;
$y = 300;
function addition()
{
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}
addition();
echo $z;
?>
</body>
</html>
Output:
800
----------------- OR -----------------
<!DOCTYPE html>
<html>
<body>
<?php
$x = 500;
$y = 300;
$p=$x+$y;
echo "The first output is = ";
echo $p;
echo "<br>";
function addition() //User defined function in php
{
$m=$x+$y; // Notice, undefined variables m,x and y.
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}
addition(); //function calling
echo $m;
echo "The second output is = ";
echo $z;
?>
</body>
</html>
Output:
The first output is = 800
Notice: Undefined variable: x in C:\xampp\htdocs\test\test1.php on line 16
Notice: Undefined variable: y in C:\xampp\htdocs\test\test1.php on line 16
Notice: Undefined variable: m in C:\xampp\htdocs\test\test1.php on line 21
The second output is = 800
----------------- OR -----------------
<!DOCTYPE html>
<html>
<body>
<?php
$x = 15;
function calc()
{
global $x;
$value = $x + 5;
echo "The output is = $value";
}
calc();
?>
</body>
</html>
The output is = 20
----------------- OR -----------------
<!DOCTYPE html>
<html>
<body>
<?php
$x = 500; //Global variable
$y = 300; //Global variable
$p=$x+$y;
echo "The first global output is = ";
echo $p;
echo "<br>";
function addition() //User defined function in php
{
$num1=10; $num2=20; //Local variable
$result=$num1+$num2;
echo "The local output is = ";
echo $result;
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}
addition(); //function calling
echo "<br>";
echo "The second global output is = ";
echo $z;
?>
</body>
</html>
The first global output is = 800
The local output is = 30
The second global output is = 800
----------------- OR -----------------
<!DOCTYPE html>
<html>
<body>
<?php
function addition() //User defined function in php
{
global $result; //Global variable
$num1=10; $num2=20; //Local variable
$result=$num1+$num2;
}
addition(); //function calling
echo "The output is = ";
echo $result;
?>
</body>
</html>
Output:
The output is = 30
----------------- OR -----------------
<!DOCTYPE html>
<html>
<body>
<?php
$x = 15;
function calc()
{
global $x;
$value = $x + 5;
echo "The output is = $value";
}
calc();
?>
</body>
</html>
Output:
The output is = 20
0 Comments