PHP Variables


Variables in PHP are not declared as int or char. Because PHP is a Loosely Typed Language, the PHP automatically converts the variable to the correct data type, depending on its value.

echo and print are used to display output values 


<?php

$X = 432;
$Y = 634;
 echo $X +$Y;
 echo "<br>";
 
 print $X +$Y;
?>


Output :

1066
106


Scope of Variables

  • PHP has three different variable scopes:
  • local
  • global
  • static


  • 1.       Global variables

Any variable declared outside a function is termed as global variable which can be accessed outside the functions in the code.

Eg

 

  • 2.       Local Variables

When a variable is declared inside the function block, it is termed as local variable and can be used only inside the scope of that function

 

<?php

$oc_global = 5; // global scope

function testCode() {
    $oc_local=43;
    echo "Variable oc_global inside function is: $oc_global</p><br>";
    echo "Variable oc_local inside function is: $oc_local</p><br>";
} 
testCode();

    echo "Variable oc_global outside function is: $oc_global</p><br>";
    echo "Variable oc_local outside function is: $oc_local</p><br>";
?>

Output:


Notice: Undefined variable: oc_global in C:\xampp\htdocs\phpCodes\variables3.php on line 8
Variable oc_global inside function is:


Variable oc_local inside function is: 43


Variable oc_global outside function is: 5



Notice: Undefined variable: oc_local in C:\xampp\htdocs\phpCodes\variables3.php on line 14
Variable oc_local outside function is:

in output it is showing error because we violated the variable scope

 

  • 3.       Static variable

Static variables are declared inside the functions. They can be reused outside the scope of function also

<?php


function testCode() {
    static $oc_static=43;
    echo "Variable oc_static inside function is: $oc_static</p><br>";
	
	$oc_static++;
} 

testCode();
testCode();
testCode();

?>

Output:

Variable oc_static inside function is: 43


Variable oc_static inside function is: 44


Variable oc_static inside function is: 45

If any of the above criteria is violated, the compiled code will show an error at execution




Related Tutorials