PHP Variables
In simple words, a variable is a name of memory location that holds data. A variable is a temporary storage that is used to store data temporarily.
What is Variables in PHP
- Areas of memory set aside by the programmer to store data and assigned a name by the programmer. These variables can then be used for such things as temporary storage during calculations.
- A PHP variable starts with the $ sign, followed by the name of the variable.
- Variables works as containers for storing data.
- A variable name can not start with a number.
- Variable name are case-sensitive(ex: $color, $COLOR both are different).
- Variable can contains alpha-numeric values and special symbols.
- PHP variables must start with letter or underscore
EXAMPLE-
<?php $x = 5; $y = 6; echo $x * $y; ?> OUTPUT: 30
Loosely Typed Language
PHP is a loosely typed language because its automatically converts variable to correct data-types.
In other languages such as C, C++, and Java, it is must to declare the name and type of the variable before using it.
Variable Declaration
$variable_name = value;
Variable Scope
Scope can be defined range of availability.Variables can be declared anywhere in the script.There are 3 type of variables in PHP.
- local variable
- global variable
- static variable
Local Variable – A Local variable declared inside a function.These variables have local scope and can not be accessed outside a function.
<?php function testFunction() { $var = 10; // local scope echo "<p>Variable var inside function is: $var</p>"; } testFunction(); echo "<p>Variable var outside function is: $var</p>"; ?> OUTPUT: Variable var inside function is: 10 Variable var outside function is:
Global Variable – A Global variable declared outside a function.These variables have Global scope and can only be accessed outside a function.
<?php $var = 10; // global scope function testFunction() { echo "<p>Variable var inside function is: $var</p>"; } testFunction(); echo "<p>Variable var outside function is: $var</p>"; ?> OUTPUT: Variable var inside function is: Variable var outside function is: 10
Static Variable –When a function is executed, its all variables are deleted. However, we want a local variable NOT to be deleted. We need it for a further job.
You can declare a variable to be static simply by placing the keyword STATIC in front of the variable name.
<?php function testFunction() { static $x = 10; echo $x; $x--; } testFunction(); echo "<br>"; testFunction(); echo "<br>"; testFunction(); ?> OUTPUT: 10 9 8