PHP Variable Scope with Example

Leave a Comment

The scope of a variable is the portion of the script in which the variable can be referenced PHP has four different variable scopes:

  1. local
  2. globle
  3. static
  4. parameter


Local Scope

A varible declared within a PHP function and can only be accessed within that function.

Example
<?
$x=4;
function assignx()
{
 $x=0;
 print"\$x inside function is $x.";
}
 assignx();
 print"\$x outside of function is $x,";
 ?>

Output of above Program
$x inside function is 0.
$x inside of function is 4.

Globle Scope

Globle scope refers to any variable that is defined outside of any function.

Globle variable can be accessed from any part of the script that is not inside a function.To access a globle variable from within a function,use the globle keyword:
<?
    $somever=15;
    function addit()
    {
      GLOBLE $somever";
      $somever++;
      print"somever is $somever";
    }
    addit();
   ?>
        
Output of above Program
Somevar is 16

Static Scope

When a function is completed,all of its variable are normally deleted.However,sometime you want a local variable to not be deleted.

To do this,use the static Keyword when you first declared the variable:
static $rememberMe;

Example
  <?
    function Keep_track()
    {
     STATIC $count=0;
     $count++;
     print $count;
     print" ";
    }
    Keep_track();
    Keep_track();
    Keep_track();
  ?>
   
Output of above Program
1
2
3

Parameters

A parameter is a local variable whose value is passed to the function by the calling code.
Parameter are declared ina paremeter list as part of the function declaratin:
  function myTest($para1,$para2,....)
  {
  //function code
  }

Example
  <?
    //multiple a value by 10 and teturn it to the caller
    functionm multiply($value)
    {
      $value=multiply(10);
      print"return value is $retval\n";
  ?>

Output of above Program
Return value is 100

0 comments:

Post a Comment