For any programming language variables are act as and storing unit / container that stores some information.Php variables always starts with the dollar ($) symbol and followed by the variable name, actually $ symbol represents the preprocessor.These Variable contains the value of its latest last assignment and will be updated if any new assignment occurred.
Php Variables can be declare as follows ” $variable_name “.
Php Variables naming conventios
- A php variable must only starts with a letter or underscore (eg.$ _phpvariable , $phpvariable).
- A php variable can only contains alphabets, numeric characters and underscores. (eg. $php_variable , $php011).
- A php variable must not have any space .
- Php Variables are case sensitive such as $php_var and $Php_Var both are two different variables.
- Php doesn’t have data types , It decide the type of variable at run time whether it have to store character or it have to store numeric, hence said Loosely Typed Language.
Php Variable Scopes
Php Variables have 4 basic scope to be accessed or to be used in a Php script.
- local
- global
- static
- parameter
Php Local Variables
Local Php variable can be accessed or to be used within the the function in which the variable is declared.
<?php $x=5; // global scope function myLocal() { $x=11; echo $x; // local scope } myLocal(); ?>
This script generates the output 11 of local variable $x within the function.
Php Global Variables
Global variables declares outside the function and can be accessed within the script anywhere.
<?php $x=5; // global scope $y=10; // global scope function myGlobal() { global $x,$y; $y=$x+$y; } myGlobal(); echo $y; // outputs 15 ?>
Php Static Variables
Generally once a function successfully executed it flush all the variables and their values, But sometimes we require to maintain last modified value of an variable after execution of function. Static variables maintain their values to be updated even after successfull execution of function.
<?php function myTest() { static $x=0; echo $x; $x++; } myTest(); myTest(); myTest(); ?>
In the above example output would be “0 1″, just because variable $j have maintain last modified value that is 1.
Php Parameter Variables
Parameters are the local variables whose value is passed by the calling functions argument.
<?php function myTest($x) { echo $x; } myTest(5); ?>