02 – PHP Variables

In PHP, variables start with $ followed by the name of the variable. You don’t need any command or keyword for declaring variables in PHP.

Like in any other programming language, there are rules for declaring variables in PHP. Variables in PHP must start with a letter or an underscore sign. They can’t start with a number. A PHP variables can contain only letters, numbers and/or underscores (alphanumeric characters). They are also case sensitive.

<!DOCTYPE html>
<html>
<body>

<?php

$a = "Hi there!";
$A = 5;
$_ = 10.5;
$_a_b = "What a name!";

echo $a;
echo "<br>";
echo $A;
echo "<br>";
echo $_;
echo "<br>";
echo $_a_b;
echo "<br>";

?>

</body>
</html>

There are three kinds of variables in PHP:

  • Local Variables
  • Global Variables
  • Static Variables

Local Variables in PHP

A PHP variable declared inside of a function can be accessed only within that function.

<!DOCTYPE html>
<html>
<body>

<?php

function myLocal() {
    $a = "A local variable"; // local scope
    echo "<p>The PHP variable a inside the function myLocal is: $a</p>";
}
myLocal();

?> 

</body>
</html>

Global Variables in PHP

A PHP variable declared outside of a function has a global scope and it can be accessed only outside a function.

<?php

$a = "Hi there!"; // global scope
 
function myGlobal() {
    // variable a is not recognize inside the function
    echo "<p>Variable a inside function is: $a</p>";
}
myGlobal();

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

?>

The global keyword in PHP

The global keyword is used to access a global variable within a function.

<?php

$a = 3;
$b = 4;

function myAddition() {
    global $a, $b;
    $c = $a + $b;
    echo $c;
}

myAddition();

?>

The $GLOBALS[] array in PHP

Global variables in PHP are stored in an array named $GLOBALS[]. Here is the previous example modified to use the $GLOBALS[] array.

<?php

$a = 3;
$b = 4;

function myAddition() {
    $c = $GLOBALS['a'] + $GLOBALS['b'];
    echo $c;
}

myAddition();

?>

The static keyword in PHP

In PHP, when a function is executed, all its variables are deleted. In order to avoid this, the static keyword is used, so the variables can be reused.

<?php

function myCountUp() {
    static $a = 5;
    echo $a;
    echo "<br>";
    $a++;
}

myCountUp();
myCountUp();
myCountUp();

?>

Leave a Reply