Variables
Local Variable
$technology = "PHP"; displayTechnology(); function displayTechnology() { $technology = "HTML"; // this is the local variable, not the one defined outside of this function
echo $technology; } echo $technology;
HTML
PHP
PHP
Global Variable
global $technology; // define global variable first and then assign the value after.
$technology = "PHP"; displayTechnology(); function displayTechnology { global $technology; // to access global variable, need to define it again.
$technology = "HTML"; // change the value of the global variable.
} echo $technology;
HTML
Another (recommended) way of accessing global variable
(See documentation of Superglobals And Predefined Variables)global $ranking; // define global variable first and then assign the value after.
$ranking = "Medium"; displayRanking(); function displayRanking { $GLOBALS['ranking'] = "Top"; // another way of accessing global variable (recommended).
} echo $ranking;
Top
Static Variable
$counter(); // prints 1
$counter(); // prints 2
$counter(); // prints 3
function counter { static $count = 0; $count = $count + 1; echo $count; }
1
2
3
2
3
Variable Variables (a variable can hold another variable)
$clientNames = "ClientA, ClientB, ClientC"; $clients = "clientNames"; echo $$clients;
ClientA, ClientB, ClientC
$clientNames = "ClientA, ClientB, ClientC"; $clients = "clientNames"; $allClients = "clients"; echo $$$allClients;
ClientA, ClientB, ClientC
isset() function
if (isset($address)) { echo $address; } else { echo "address variable is not defined."; }
address variable is not defined.