Sunday, March 15, 2009

Variables in PHP

In any programming language variables are the declaration which stands for value. In PHP, variables can be declared to store numbers, characters or any values. Variables can be used as many as you wish inside the script.

  • In PHP all variables must start with $ sign. But we don't need to declare the data type of the variables. PHP automatically converts the variable to the correct data type, depending on how they are set. That's why PHP is called loosely typed language.
  • The variable name in PHP is case-sensitive.
  • A variable name must start with a letter or an underscore "_"
  • A variable name can only contain alpha-numeric characters and underscores (a-z, A-Z, 0-9, _ and the bytes from 127 through 255 (0x7f-0xff). )
  • It should not contain spaces.
  • $this is a special variable that can't be assigned. By default, variables are always assigned by value. Note that PHP offers assignment of values to the variable by two ways, 1) Assign by expression. 2) Assign by reference (simply prepend an ampersand (&) to the beginning of the variable which is being assigned).

Following is an example of PHP variables using and displaying the value of the variables.

<html>
<body>
<?php
$variable1='This is string type variable';
$_variable2=100;
echo $variable1 . "<br />";
echo $_variable2. "<br />";

$variable3=&$_variable2;
$variable4=$_variable2;
echo "Variable3 value:" . $variable3 . "<br />";
echo "variable4 value:" . $variable4. "<br />";
$_variable2=200;
echo "After assignment to _variable2 Variable3 value:" . $variable3. "<br />";
echo "After assignment to _variable2 variable4 value:" . $variable4;
?>
</body>
</html>

The following is the output.

This is string type variable
100
Variable3 value:100
variable4 value:100
After assignment to _variable2 Variable3 value:200
After assignment to _variable2 variable4 value:100

Note that, in the case of "assign by reference" the value of the variable is change if reference value is changed but in case of "assign by expression" if source changes has no effect on assigned variable.

Related Documents
Datatypes in Php
Integer and floating point number in Php
Magic constants in php
Boolean datatype in Php

No comments:

Post a Comment