PHP has three different variable scopes:
Global :-A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function.
Static :-
A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope.
Local :-
A variable declared within a function has a LOCAL SCOPE and can only be accessed within that function.
Example - local and global scope :
<?php
$a=15; // global scope
function Test()
{
$b=10; // local
scope
echo "<p>Test variables inside the
function:<p>";
echo "Variable a is: $a";
echo "<hr/>";
echo "Variable b is: $b";
}
Test();
echo "<p>Test variables outside the
function:<p>";
echo "Variable a is: $a";
echo "<hr/>";
echo "Variable b is: $b";
?>
The global keyword –
<?php
$a=15;
$b=10;
function Test()
{
global $a,$b;
$b=$a+$b;
}
Test();
echo $b;
?>
The static keyword -
<?php
function Test()
{
static $a=0;
echo $a;
$a++;
}
Test();
Test();
Test();
?>
Comments
Post a Comment