PHP Variable Declaration

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:

$var = "November";
$var = 70;
$var = array('January', 'February', 'March');	

Rules for variables declearation

  • Variable always starts with the $ sign, followed by the variable name.
  • Variable name must start with a letter or the underscore character.
  • Variable name cannot start with a number.
  • Variable name can only allow alpha-numeric characters and underscores (A-z, 0-9, and _ ) other special character not allowed.
  • Variable names are case sensitive ($var and $VAR are two different variables).

Variable Variables

In php you can reference the value of a variable whose name is stored in another variable.For example

$var = 'iop';
$$var = 'vip';	

When second statement executes, the variable $iop has the value "vip"

Variable Scope

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.

Local scope

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 = 34;
update_inside_var( );
echo $var_inside_function;

When run the above PHP code, it will produce following result


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.

Global scope

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;
var_inside_function( );
echo $counter;

When run the above PHP code, it will produce following result


Static variables

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;
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