Using Global Variable in a Function in PHP

$GLOBALS or global is one of the superglobal variables,which has a global access .i.e.,it can be referred from anywhere.

Source code :


<?php
 $str = "Global string"; 
   
   function globalexample() {
      global $str; // make the $str as global variable
      print $str;
   }
   
  globalexample();



Output :

Global string

Notes :

Making it as Global ,we insist the PHP to consider the already existing variable as global and use it wherever you want.

<?php

 $str = "Global string"; 

   function globalexample() {

      print $str; 
   }

  globalexample(); 

The above code prints nothing because the variable has no scope inside the function.


Output :


                

Comments :