DEV Community

Cover image for Variable & Variable Scope | PHP Fundamentals
Gunawan Efendi
Gunawan Efendi

Posted on • Edited on

Variable & Variable Scope | PHP Fundamentals

Create Variable in PHP

The rules when you create variables in PHP:

  1. Variable declaration with dollar ($) followed by variable name
  2. Variable name must start with a letter or underscore (_)
  3. Variable name is case-sensitive

Valid variables:

$name = "Gunawan"; //valid
$Name = "Gunawan"; //valid
$_name = "Gunawan; //valid
Enter fullscreen mode Exit fullscreen mode

Not valid variables:

$4name = "Gunawan"; //not valid
$user-name = "Gunawan"; //not valid
$this = "Gunawan"; //not valid
Enter fullscreen mode Exit fullscreen mode

Variable Scope

PHP has 3 variable scopes:

  1. Global
  2. Local
  3. Static

Global scope

$name = "Gunawan";

function get_name() {
echo $name; // not valid
}

get_name();
Enter fullscreen mode Exit fullscreen mode

To access a global variable within a function you must declare a global variable with the keyword 'global' within a function.

$name = "Gunawan";

function get_name() {
global $name;
echo $name; // valid
}

get_name();
Enter fullscreen mode Exit fullscreen mode

Use Array GLOBALS to Access Global Variable

The second way to access global variables is to use a global array.

$name = "Gunawan";

function get_name() {
echo $GLOBALS['name']; // valid
}

get_name();
Enter fullscreen mode Exit fullscreen mode

Static Variable

function test() {
static $number = 0;
echo $number;
$number++;
}
Enter fullscreen mode Exit fullscreen mode

Variable Super Global in PHP:

  1. $GLOBALS
  2. $_SERVER
  3. $_GET
  4. $_POST
  5. $_FILES
  6. $_COOKIE
  7. $_SESSION
  8. $_REQUEST
  9. $_ENV

Download my repository php fundamental from my github.

Top comments (0)