How to declare a global variable in PHP?


A global variable can be accessed in any part of the program. However, in order to be modified, a global variable must be explicitly declared to be global in the function in which it is to be modified. This is accomplished, conveniently enough, by placing the keyword GLOBAL in front of the variable that should be recognized as global.

Example

The code is as follows wherein we can see how to declare a global variable in PHP−

 Live Demo

<?php
   $val = 1;
   function display() {
      GLOBAL $val;
      $val++;
      print "Value = $val";
   }
   display();
?>

Output

This will produce the following output−

Value = 2

Example

Let us now see another example−

 Live Demo

<?php
   $a = 2;
   $b = 3;
   function display() {
      global $a, $b;
      $b = $a + $b;
   }
   display();
   echo $b;
?>

Output

This will produce the following output−

5

Updated on: 02-Jan-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements