PHP variable in a program is used to store data, like a string of text, numbers, etc. Following are some important things to know about variables:
- The PHP variables do not need to be declared before adding value to it. The PHP automatically converts the variables to the correct data types, depending on its value.
- The declared variable can be reused throughout the code.
- By using the assignment operator (=), assign value to a variable.
Example:
The variable can be declared as: $var_name = value.
In this example we have created two variables where first one has assigned with a string value and the second has assigned with a number.
<?php
// Declaring variables
$myVariable = "Hello PHP!";
$variable1 = 15;
// Displaying variables value
echo $myVariable; // Output: Hello PHP!
echo $variable1; // Output: 15
?>
Rules for Variable declaration:
- All variables in PHP must begin with a dollar sign ($), followed by the variable name.
- A variable can have long descriptive names like $firstvariable, $even_odd or short names like $n or $f or $x.
- A variable name only contain alpha-numeric characters and underscores (i.e., ‘a-z’, ‘A-Z’, ‘0-9 and ‘_’) in their name.
- A variable name cannot start with a number.
- If variable contain more than one word then it should be seperated with underscores. i.e. $first_variable
- If variable contain more than one word then it should be distinguished with capitalization. i.e. $firstVariable
PHP Variables Scope:
The variables can be declared anywhere in the program in PHP. We declare the variables for a particular scope. The following are the types of scope.
Local variables:
A variables declared within a function are considered as local variables to that function and has its scope only in that particular function means it cannot be accessed outside that function.
Example:
<?php
$x = 20;
function local_var()
{
// local scope
$x = 30; // local variable
echo "local num = $x \n"; // output= 30
}
local_var();
echo "Variable num outside local_var() is $x \n"; // output= 20
?>
Global variables:
A variables declared outside a function are considered as global variables. To use this variable within a function we need to use the “global” keyword before the variable to refer to the global variable.
Example:
<?php
$x = 20;
function global_var()
{
global $x;
echo "Variable num inside function : $x \n"; // output= 20
}
global_var();
echo "Variable num outside function : $x \n"; // output= 20
?>
Static variable:
Normally, when a function terminates, all of its variables delete its values. But sometimes we want to store these values for further jobs. The variables which hold the values are called static variables. To do this we must use the keyword “static” in front of those variables.
Example:
<?php
function static_var()
{
static $x=1;
echo $x;
$x++;
}
static_var()
echo "<br>";
static_var()
echo "<br>";
static_var()
?>