You are here: Home / Topics / How to declare a global variable in PHP

How to declare a global variable in PHP

Filed under: PHP on 2023-06-30 06:28:16

Global variables refer to any variable defined outside the function. Global variables are accessible from any part of the script, i.e. inside and outside the function.

There are two ways to access a global variable inside a function:

  • Using the global keyword
  • Using the array GLOBALS[var_name]: It stores all global variables in an array called GLOBALS[var_name]. var_name is the name of the variable. This array is also accessible from functions and can be used to perform operations on global variables directly.

How to declare a global variable in PHP


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

Output:

3


About Author:
V
Vinay Kumar     View Profile
Hi, I am using MCQ Buddy. I love to share content on this website.