A variable is used for holding information during the execution of PHP scripts. In PHP, variables are denoted with dollar sign ($) in the beginning. Unlike javascript or other languages, we don’t precede variable name with any qualifier such as int, char, var etc.
In PHP, echo or print statements are used to output the value of variable to the screen, which is usually a web page.
<?php
$KH_Name = "John";
echo "My name is : " . $KH_Name . "<br>";
print ("My name is : $KH_Name");
?>
Variable can be declared anywhere in the PHP script. However, the scope of variable varies depending on the position of its declaration. In PHP, there are three types of variable scope:
In the below example, variable $KH_Name is declared within function. It can be accessed within function only. The usage of variable outside the function will generate an error.
<?php
function KH_DisplayMyName() {
$KH_Name = "John"; // local scope
echo "Display my name inside the function: $KH_Name<br>";
}
KH_DisplayMyName();
// Access of $KH_Name variable will display an error
echo "Display my name outside the function: $KH_Name<br>";
?>
The global variable can be accessed through global keyword within the function. In the below example, global keyword is used before the variable $KH_Name.
<?php
$KH_Name = "John"; // Global scope
function KH_DisplayMyName() {
global $KH_Name;
echo "Display my name inside the function: $KH_Name<br>";
}
KH_DisplayMyName();
echo "Display my name outside the function: $KH_Name<br>";
?>
As soon as the execution of function is completed, the scope of all variables declared within the function ends and we lose their values as well. Sometimes, it is required to hold the value of local variable for further process. It can be achieved by using static keyword in front of the variable while declaring or assigning the values for the first time.
<?php
function KH_DisplayCount() {
static $KH_Count = 1;
echo "Counter value : $KH_Count<br>";
$KH_Count ++;
}
KH_DisplayCount(); // Output: Counter value : 1
KH_DisplayCount(); // Output: Counter value : 2
KH_DisplayCount(); // Output: Counter value : 3
KH_DisplayCount(); // Output: Counter value : 4
?>