December 30, 2025|PHP|

When working with PHP functions, one of the most common points of confusion for beginners is variable scope—specifically, how and where variables can be accessed. PHP variables can have global scope or local scope, and understanding the difference is essential for writing bug-free and maintainable code.

In this example, we’ll explore how variables declared outside a function behave differently from variables used inside a function. We’ll also see how PHP provides the special $GLOBALS superglobal array, which allows us to access global variables from anywhere in the script, including inside functions.

The following code demonstrates:

  • How global variables are defined
  • Why they are not directly accessible inside a function
  • How $GLOBALS can be used to access them safely
  • The difference between accessing variables inside and outside a function

Let’s look at the code in action 👇

<?php
$x = 5; // global scope
$y = 5; 
function myTest() {
	//global $x;

	echo "<pre>";
	print_r($GLOBALS);
	echo $GLOBALS['x'];
	echo $GLOBALS['y'];
	echo "</pre>";
  // using x inside this function will generate an error
  //echo "<p>Variable x inside function is:" . $x .". </p>";
} 
myTest();

echo "<p>Variable x outside function is: $x</p>";

/*A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function:
A variable declared within a function has a LOCAL SCOPE and can only be accessed within that function:
*/
?>

- END -


One Comment

  1. 20bet September 5, 2023 at 4:12 pm - Reply

    Your article gave me a lot of inspiration, I hope you can explain your point of view in more detail, because I have some doubts, thank you.

Leave A Comment

Get fresh content from StatelyWorld