HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

PHP $GLOBALS

$GLOBALS variables can have different scopes, which determine their accessibility within your code.



Global Variables declared outside any function, class, or block of code with the global keyword.

Superglobals : Predefined variables in PHP that are available everywhere in your script, regardless of scope. They don't require any special declaration.

To use a global variable inside a function you have to either define them as global with the global keyword, or refer to them by using the $GLOBALS syntax.


Example


Refer to the global variable $x inside a function:

<!DOCTYPE html>
<html>
<body>

<?php  
$x = 75;
  
function myfunction() {
  echo $GLOBALS['x'];
}

myfunction()
?>  

</body>
</html>

Output

75

This is different from other programming languages where global variables are available without specifically referring to them as global.


Example


In PHP you get nothing (or an error) when referring to a global variable without the $GLOBALS syntax:

<!DOCTYPE html>
<html>
<body>

<?php  
$x = 75;
  
function myfunction() {
  echo $x;
}

myfunction()
?>  

</body>
</html>


• Create Global Variables


Variables created in the outer most scope are global variables either if they are created using the $GLOBALS syntax or not:

Example


In PHP you get nothing (or an error) when referring to a global variable without the $GLOBALS syntax:

<!DOCTYPE html>
<html>
<body>

<?php  
$x = 100;

echo $GLOBALS["x"];
echo $x;
?>  

</body>
</html>

Output

100100

Variables created inside a function belongs only to that function, but you can create global variables inside a function by using the $GLOBALS syntax:


Example


Create a global variable from inside a function, and use it outside of the function:

<!DOCTYPE html>
<html>
<body>

<?php  
function myfunction() {
  $GLOBALS["x"] = 100;
}

myfunction();

echo $GLOBALS["x"];
echo $x;?>  

</body>
</html>

Output

100100