How to define and use Global variables in PHP function

In PHP global variables are ones defined outside of functions. They can be accessed and have value modified inside or outside of a function.

Global variables are defined like normal ones. But to access them inside functions, we need to use a certain method:

  • Use global keyword
  • Use array GLOBALS[variable_name]
$num = 100;
function updateNum(){
	global $num;
	$num += 200;
}
updateNum();
echo $num;
//output: 300
$brand = 'Samsung';
function showModel(){
	if($GLOBALS['brand'] == 'Samsung'){
		echo 'Galaxy S21';
	}
}

showModel();
//output: Galaxy S21

Leave a Comment

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

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close