PHP variables scope

 In PHP , Variables can be declared anywhere in the script. The scope of a variable is the context within which it is defined.

PHP has three different variable scope.

A- Global

B- Local

C- Static


Local and Global Scope

<?php
$a 
1;
include 
'b.inc';
?>

 Here $a variable available within the included 'b.inc' file

<?php

$m = 5// global scope

function variableTest() {
  // using m inside this function will generate an error
  echo "<p>Variable m inside function is: $m</p>";
}
variableTest();

echo "<p>Variable m outside function is: $m</p>";
?>

A variable declared outside a function has a Global Scope and can only be accessed outside function. 

<?php
function variableTest() {
  $m = 5// local scope
  echo "<p>Variable m inside function is: $m</p>";
}
variableTest();

// using m outside the function will generate an error
echo "<p>Variable m outside function is: $m</p>";
?>

A Variable declared within a function has a local scope and can be accessed only within that function.

The global keyword

The global keyword is used to access a global variable from within a function.

For this use global keyword before the variable (inside the function).

<?php
$a 
1;
$b 2;

function 
Sum()
{
    global 
$a$b;

    
$b $a $b;


Sum();
echo 
$b; // output 3
?>

PHP also store all global variable in an array $GLOBALS[index]. The index hold name of the variable. This array is also accessible within that function.

The above example can be written like this.

<?php
$a 
1;
$b 2;

function 
Sum()
{
  


    
$GLOBALS['b'] $GLOBALS['a'] $GLOBALS['b'];


Sum();
echo 
$b; // output 3
?>

The static Keyword

Another important feature of variable scoping is the static variable.

Normally when a function executed/completed, all of its variable deleted. Sometimes we want to need local variable not to be deleted or not lose.

To do this use static keyword when you first declare the variable.

Example -

<?php
function variableTest() {
  static $x = 0;
  echo $x;
  $x++;
}

variableTest();   // output 0
variableTest();   // output 1
variableTest();   // output 2
?>

Then, each time the function is called, that variable will still have the information it contained from the last time the function was called.

Write a program in PHP to reverse a number

A number can be written in reverse order. For example 12345 = 54321 <?php   $ num = 23456;   $ revnum = 0;   while ($ num > 1)   {   $...