PHP variables:

  • A variable starts with the $ sign, followed by the name of the variable
  • A variable name must start with a letter or the underscore character
  • A variable name cannot start with a number
  • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
  • Variable names are case-sensitive ($age and $AGE are two different variables)
  • Automatically converts the variable to the correct data type, depending on its value.

Example:

<!DOCTYPE html>
<html>
<body>

<?php
$txt = "Hello World!";
$x = 5;
$y = 10.5;

echo $txt;
echo "<br>";
echo $x;
echo "<br>";
echo $y;
echo "This is $txt!";​
echo "This is " . $txt . "!";​
echo $x + $y;

?>

<?php
$x = 5; // global scope

function myTest() {
    // using x inside this function will generate an error
    echo "<p>Variable x inside function is: $x</p>";

myTest();

echo "<p>Variable x outside function is: $x</p>";

?>

<?php
function myTest() {
    $x = 5; // local scope
    echo "<p>Variable x inside function is: $x</p>";

myTest();

// using x outside the function will generate an error
echo "<p>Variable x outside function is: $x</p>";

?>

<?php

//Global variables can be accessed inside function using global keyward
$x = 5;
$y = 10;

function myTest() {
    global $x, $y;
    $y = $x + $y;
}

myTest();
echo $y; // outputs 15

?>

<?php
$x = 5;
$y = 10;

function myTest() {
    $GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];


myTest();
echo $y; // outputs 15

?>

<?php
function myTest() {
    static $x = 0;
    echo $x;
    $x++;
}

myTest();
myTest();
myTest();

?>
</body>
</html>

Variable scopes:

  • Local

    • A variable declared within a function has a LOCAL SCOPE and can only be accessed within that function
  • Global

    • A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function
    • All global variables in an array called $GLOBALS[index]. The index holds the name of the variable. This array is also accessible from within functions and can be used to update global variables directly.
  • Static

    • All of its variables are deleted when a function is completed/executed. However, sometimes we want a local variable NOT to be deleted, for that, we have to use static keyword.