Curriculum
Course: PHP Basic
Login

Curriculum

PHP Basic

PHP Install

0/1

PHP Casting

0/1

PHP Constants

0/1

PHP Magic Constants

0/1

PHP Operators

0/1

PHP Reference

0/276
Text lesson

$GLOBALS

Global Variables

Global variables are accessible from any scope.

Variables defined in the outermost scope are automatically global and can be used in any scope, such as within a function.

To use a global variable inside a function, you must either declare it as global with the global keyword or access it using the $GLOBALS array.

Example

Access the global variable xx inside a function:

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

This differs from other programming languages, where global variables are accessible without explicitly referring to them as global.

Example

In PHP, referring to a global variable without using the $GLOBALS syntax results in either nothing or an error.

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

You can also access global variables within functions by declaring them as global using the global keyword.

Example

Declare xx as global within a function:

$x = 75;
function myfunction() {
 global $x;
 echo $x;
}
myfunction()

Create Global Variables

Variables created in the outermost scope are global variables, whether they are defined using the $GLOBALS syntax or not.

Example

$x = 100;

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

Variables created inside a function belong exclusively to that function; however, you can create global variables within a function by using the $GLOBALS syntax.

Example

Define a global variable within a function and use it outside the function:

function myfunction() {
 $GLOBALS["x"] = 100;
}
myfunction();
echo $GLOBALS["x"];
echo $x;