How to access variable outside of function in PHP?

Member

by gilbert , in category: PHP General , a year ago

How to access variable outside of function in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by darion , 9 months ago

@gilbert 

To access a variable outside of a function in PHP, you can simply use the global keyword. For example:

1
2
3
4
5
6
7
8
$x = 10;

function myFunction() {
  global $x;
  echo $x;
}

myFunction();  // outputs 10


Alternatively, you can use the $GLOBALS array to access global variables from within a function. The $GLOBALS array is an associative array that contains a reference to all variables that are currently defined in the global scope. For example:

1
2
3
4
5
6
7
$x = 10;

function myFunction() {
  echo $GLOBALS['x'];
}

myFunction();  // outputs 10


Keep in mind that global variables can be overridden by local variables with the same name, so it's generally a good idea to avoid using global variables if possible.