PHP Variables
PHP Variable is the name of memory location used to hold the data. In PHP, variable starts with $ symbol. Rules for PHP Variables.
- Variable starts with $ sign.
- Variable name must start with a letter or the underscore character.
- Variable name can contain alpha-numeric character (A-Z. 0-9).
- Variable name are case-sensitive ($name and $NAME are two different variables).
<?php $name = "RasmusLerdorf"; echo "PHP Father: $name"; ?>Output PHP Father: RasmusLerdorf In PHP, there are three variables:
- local variable
- global variable
- static variable
<?php function fun() { $x = 10; // local scope echo "<p> x variable inside of the function: $x</p>"; } fun(); // Generate an error because x is outside the function echo "<p> x variable outside of the function: $x</p>"; ?>Output x variable inside of the function: 10 Notice: Undefined variable: x in C:\xampp\htdocs\crud\HELLO.PHP on line 8 x variable outside of the function: Global Variable The Global is a keyword that is used to access global variable within a function. Example:
<?php $x = 10; // global variable $y = 5; // global variable $z=5; // global variable function fun() { global $x, $y,$z; $y = $x * $y+$z; } fun(); echo $y; // outputs 55 ?>Output 55 Static variable Php static is a keyword that is used to create a static variable. Static variable is not be deleted when a function is completed /executed. Example
<?php function fun() { static $val = 0; echo $val; $val++; } fun(); echo "<br>"; fun(); // call function echo "<br>"; fun(); // call function echo "<br>"; ?>Output 0 1 2