Begin Web Programming with PHP & MySQL

Advertisements



PHP Variables

A variable is a container for a particular set of bits or types of data (like integer, float, string etc...). A variable is associated with or identified by a memory address. In PHP, variables can be declared anywhere in the script using a ‘$’ sign, followed by the name of the variable. PHP is a loosely typed language; it means we do not require to declare the data types of variables.

Eg: $x = 5; Here we declare a PHP variable ‘x’ and assign a value 5.

Rules for declaring PHP variables
  1. It starts with the $ sign, followed by the name of the variable.
  2. It must start with a letter or the underscore character.
  3. A PHP variable name cannot start with a number.
  4. A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ).
  5. PHP variables are case-sensitive ($x and $X are two different variables).
Scope of the variables
  • Local
  • Global
  • Static
Local variables

The variables that are declared within a function are called local variables of the function. We can declare variables with the same name in different functions, because local variables are available only for the function in which they are declared. The variable is said to have a local scope.

Eg:
<?php
function local_var_eg()
{
$local_num = 10;
$local_str = "Hello World";
echo "Local variable value: ".$local_num.", local string is: ".$local_str;
}
local_var_eg(); // calling the function
?>

Global variables

Variables which are declared outside the function are called global variables. Global variables can be accessed anywhere inside a PHP program. If you want to call a global variable within a function, we need to use the keyword “global” before the variable, to refer to the global variable.

Eg:
<?php
$a = 15;
$b = 5;
function globVar()
{
global $a, $b;
$a = $a + $b;
}
globVar();
echo $a; //new value of variable $a - outputs 20
?>

Static variables

It is the characteristic of PHP to delete the variable, once it completes its execution and the memory is freed. Sometimes we need to store the variables even after the completion of function execution. We use the ‘static’ keyword before the variable and this variable is called a static variable.

Eg:
<?php
function static_var()
{
static $x = 1;
echo $x;
$x++;
}
static_var();
echo "<br>";
static_var();
?>