Variable is a symbol or name that stores a value. Variables are used for storing values such as numeric values, characters, character strings, or memory addresses so that they can be used in any part of the program.
All variables in PHP starts with dollor ($) symbol like $name.
A valid variable name starts with a letter (A-Z, a-z) or underscore (_), followed by any number of letters, numbers, or underscores.
First one is the interger variable and second one is the string variable. String variables used single or double quotes(‘’, “”) for a value.
Variable naming conventions
There are a few rules for declaring a variable name:
Note: In language such as C, C++ you have to declare the name and type of the variable before use it. In PHP the type of the variable does not need to be declared before use it, because types are associated with values rather than variables. As a result a variable can change the type of its value as much as we want.
In the following example none of the variables are declared before they are used, fact is $height is floating number and $width is an integer.
Assigning by Reference
This means that the new variable simply points the original variable. Changes to the new variable affect the original, and vice a versa.
Scope of Variable:
Variables can be declared anywhere in the script. There are two types of scope,
There are two echo statements inside var_scope() function. It prints the value of $y as it is the locally declared and can not prints the value of $x since it is created outside the function.
The next statement of the script prints the value of $x since it is global variable i.e. not created inside any function.
The last echo statement can not prints the value of $y since it is local variable and it is created inside the function var_scope() function.
The global keyword is used to access a global variable within a function.
PHP also stores all global variables in an array called $GLOBALS[index]. The index holds the name of the variable. This array is also accessible from within functions and can be used to update global variables directly.
Generally, when a function terminates, all of its variable loose its values. If you want that variables hold these values for further use, you have to declare this variable as static.
“static” is predefine keyword used to making any variable static.
Then, each time the function is called, that variable will still have the information it contained from the last time the function was called.