PHP Variables Scope


PHP has three different variable scopes:

local
global
static

Local Variable: A variable declared within a functionor any body means with in{ } has a LOCAL SCOPE with in the{ } and can only be accessed with in that function or body.
Global Variables:   the  variable declared outside  inside the php tag and outside of any function is called global variable normally at the starting of  script . these variable are available in all function body and can be accessed by global keyword within a function.
<?php
$x = 5;
$y = 10;
function myTest() {
    global $x, $y;
    $y = $x + $y;
}
Static Variables: Normally, when a function is completed/executed, all of its variables are deleted. However, sometimes we want a local variable NOT to be deleted. We need it for a further job. We can achive by declaring these variable static.
<?php
function myTest() {
    static $x = 0;
    echo $x;
    $x++;
}
myTest();
myTest();
myTest();
?>

No comments:

| Designed by Harhiktech