Open In App

PHP | Variables

Variables

Variables in a program are used to store some values or data that can be used later in a program. The variables are also like containers that store character values, numeric values, memory addresses, and strings. PHP has its own way of declaring and storing variables. 
There are a few rules, that need to be followed and facts that need to be kept in mind while dealing with variables in PHP:  



Data types used by PHP to declare or construct variables:

Example: 
 






<?php
 
$num = 20;
 
// function to demonstrate use of global variable
function global_var()
{
    // we have to use global keyword before
    // the variable $num to access within
    // the function
    global $num;
     
    echo "Variable num inside function : $num \n";
}
 
global_var();
 
echo "Variable num outside function : $num \n";
 
?>

Variable Scopes

Scope of a variable is defined as its extent in a program within which it can be accessed, i.e. the scope of a variable is the portion of the program within which it is visible or can be accessed. 
Depending on the scopes, PHP has three variable scopes: 
 

Example: 
 




<?php
 
// function to demonstrate static variables
function static_var()
{  
    // static variable
    static $num = 5;
    $sum = 2;
     
    $sum++;
    $num++;
     
    echo $num, "\n";
    echo $sum, "\n";
}
 
// first function call
static_var();
 
// second function call
static_var();
 
?>

Output: 

local num = 50 
Variable num outside local_var() is 60 

Example: 
 




<?php
   $a = 'hello'; //hello is value of variable $a
   $$a = 'World'; //$($a) is equals to $(hello)
   echo $hello; //$hello is World i.e. $hello is new variable with value 'World'
?>

Output: 
 

Variable num inside function : 20 
Variable num outside function : 20 

Static variable: It is the characteristic of PHP to delete the variable, once it completes its execution and the memory is freed. But sometimes we need to store the variables even after the completion of function execution. To do this we use the static keywords and the variables are then called static variables.  PHP associates a data type depending on the value for the variable.
 

Example: 
 





Output: 

6
3
7
3

You must have noticed that $num regularly increments even after the first function call but $sum doesn’t. This is because $sum is not static, and its memory is freed after the execution of the first function call. 
 

Variable Variables:-

Example:




<?php
   $a = 'hello'; //hello is value of variable $a
   $$a = 'World'; //$($a) is equals to $(hello)
   echo $hello; //$hello is World i.e. $hello is new variable with value 'World'
?>

Output:

World

 


Article Tags :