Previous | Home | Next |
Variables
Variable is a symbol or name that stands for 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.
Variables in PHP are represented by a dollar sign "($)" followed by the name of the variable. Variables are assigned with the = operator, with the variable on the left-hand side and the expression to be evaluated on the right. The variable name is case-sensitive.Variable Scope:
Scope can be defined as the range of availability a variable has to the program in which it is declared. PHP variables can be one of four scope types:
- Local variables
- Global variables
- Static variables
- Function parameter
Local Variable: A local variable is declared in a function; it can also be referenced as solely in function.
Example :
<? $x = 10; function assignx () { $x = 0; echo "$x inside function is $x."; } assignx(); echo "$x outside of function is $x."; ?>
Output:
$x inside function is 0. $x outside of function is 10.
Global Variables: A global variable can be accessed in any part of the program. In order to be modified, a global variable must be explicitly declared to in the function in which it is to be modified. It can be done by using the keyword GLOBAL before variable.
Example
<? $var1 = 20; function addit() { GLOBAL $var1; $var1++; echo "Variable is $var1"; } addit(); ?>
Output:
Function Parameter: Function parameters are declared after the function name and inside parentheses.A function is a small unit of program which can take some input in the form of parameters and may return some value after some processing.
Example:
<? function addition ($value) { $value = $value + 12; return $value; } $return_value = addition (50); Print "Return value is $return_value\n"; ?>
Output:
Static Variable: A static variables are declared as function parameters, which are destroyed on the function's exit, a static variable will not lose its value when the function exits and will still hold that value should the function be called again. A static variable is declared by using keyword STATIC before the variable name.
Example:
<? function counting() { STATIC $count = 0; $count++; echo $count; echo ""; } counting(); counting(); counting(); ?>
Output:
1 2 3
Variable Naming:
Variable names must begin with a letter or underscore character. A variable name can consist of numbers, letters, underscores but you cannot use characters like + , - , % , ( , ) . & , etc. There is no size limit for variables.
Previous | Home | Next |