In PHP, variables are identifiers, prefixed with a dollar sign ($). A variables is used to hold any types of value, no compile- or runtime type checking on variables. In PHP you can replace a variable's value with another type (no explict conversion require). There is no specific techniq for variable declaration in PHP. For example:
<?php $customer $address $_debugging $MAXIMUM_SIZE ?>
<?php $var = "November"; $var = 70; $var = array('January', 'February', 'March'); ?>
In php you can reference the value of a variable whose name is stored in another variable.For example
<?php $var = 'iop'; $$var = 'vip'; ?>
When second statement executes, the variable $iop has the value "vip"
In PHP scope of a variable is depend on variable declaration and there accessibility. Basically four types of variable scope in PHP: local, global, static, and function parameters.
A variable declared in side a function is local to that function and can not access outside function.
function update_inside_var ( ) { $var_inside_function++; } $var_inside_function = 34; update_inside_var( ); echo $var_inside_function;
When run the above PHP code, it will produce following result
34
In the above example we decleared two variables, inside a function and outside a function with the same name. Then, we are assigning value to the variable decleared outside the function and printing value of the variable. Since variable decleared inside function is local to that function will not increase variable value.
A variable declared outside a function are global and they can be accessed any part of the program. By default variable declared outside function are global and are not available inside function. A global variable must be explicitly declared to be global inside the function.
$counter = 100; function var_inside_function ( ) { global $counter; $counter++; } var_inside_function( ); echo $counter;
When run the above PHP code, it will produce following result
101
Sometimes we need a variable that can maintain the value between function call and available to the program. Then, we need to declare a variable static with the static keyword.
function update_static_var ( ) { static $counter = 0; $counter++; echo "Static counter is now $counter\n"; } $counter = 10; update_static_var( ); update_static_var( ); echo "Global counter is $counter\n";
When run the above PHP code, it will produce following result
Static counter is now 1 Static counter is now 2 Global counter is 10