How to declare a global variable in PHP

In this tutorial, we are going to see how to declare a global variable in PHP. 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
	$a = 1;
	$b = 2;

	function fun()
		global $a, $b;
		$b = $a + $b;

	echo $b;


mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *