PHP $GLOBALS

0
7K

$GLOBALS is an array that contains all global variables.


Global Variables

Global variables are variables that can be accessed from any scope.

Variables of the outer most scope are automatically global variables, and can be used by any scope, e.g. inside a function.

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.

ExampleGet your own PHP Server

Refer to the global variable $x inside a function:

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

myfunction()
Try it Yourself »

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:

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

myfunction()
Try it Yourself »

You can also refer to global variables inside functions by defining them as global with the global keyword.

Example

Define $x as global inside a function:

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

myfunction()
Try it Yourself »

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

$x = 100;

echo $GLOBALS["x"];
echo $x;
Try it Yourself »

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:

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

myfunction();

echo $GLOBALS["x"];
echo $x;
Try it Yourself »
Căutare
Categorii
Citeste mai mult
Alte
PHP Loops
In the following chapters you will learn how to repeat code by using loops in PHP. PHP Loops...
By PHP Tutorial 2024-05-17 07:48:35 0 4K
Alte
PHP Installation
What Do I Need? To start using PHP, you can: Find a web host with PHP and MySQL support...
By PHP Tutorial 2024-05-17 07:09:40 0 5K
Alte
PHP Data Types
PHP Data Types Variables can store data of different types, and different data types can do...
By PHP Tutorial 2024-05-17 07:27:24 0 5K
Alte
PHP Update Array Items
Update Array Item To update an existing array item, you can refer to the index number for...
By PHP Tutorial 2024-05-17 08:02:49 0 7K
Alte
الثورة البلوكتشين وتحولاتها في الصناعات المختلفة
مقدمة: شهدت تقنية البلوكتشين ثورة هائلة في السنوات الأخيرة، حيث أصبحت لديها القدرة على تغيير...
By MOHAMED ATTALLAH 2024-05-14 14:03:03 0 7K
Sociallez https://sociallez.com