JavaScript Tutorial

Variables

Variables are used to store data which are further used and manipulated as per requirement or instructions. In PHP,  a variable name is declared with a $ symbol and is followed by the variable name. It can be assigned a value using Assignment Operator (=). Syntax of declaring and defining PHP variable is:

$variableName = value;

However, there are some rules to follow while declaring a variable name in PHP which are mentioned below:

  • As discussed earlier, a variable name must start with a ‘$’ symbol, followed by the name of its variable.
  • Variable names are case sensitive. i.e. $var is different from $VAR;
  • A variable name must start with a letter or an underscore (_) followed by letters, numbers or underscores.
  • A variable name cannot contain whitespace.

Variable declaration in PHP

Code Example

Assign By Reference

In PHP, we can also assign values to the variables by reference. The newly created variable becomes an alias for the original variable. If we change the value of a new variable it will affect the value of the original variable as well and vice-versa. The syntax looks like:

Code Example

Note: In PHP, if variables are not initialized they are supposed to have default values of the context in which they are used.

For example: Integers and floats are set to zero by default, arrays and strings are empty if not initialized and a boolean is set to false.

Variable scope

Scope can be defined as the visibility of a variable throughout the program where it can be used or referenced. Three PHP variable scopes are as listed below:

1. Local Variables

The variables whose scope or visibility is limited within the function or module, are referred as local variables. Either they can be declared inside the method or passed as an argument.

2. Global Variables

The variables which are accessible throughout the program are known as Global Variables. These variables must be declared outside the function in a way the other variables are declared. There are two methods of accessing global variables in PHP.

  • Using global keyword
  • Using array GLOBALS[var_name] where var_name is the name of a variable.

3. Static Variables

The lifetime of a variable is limited to the block in which it is declared but in some cases we want to preserve the value of the variable throughout the execution of the program, Static Variables serve the same purpose. The variables are declared with a static keyword. The syntax looks like:

Function funSaticScope() is called three times but the variable $num is initialized only once and is retaining its old value each time it is called.

Go back to Previous Course