Variable Scope

Global Scope

The global scope spans all included files. That is, $foo will be visible in file.php.
<?php
    $foo = 1;
    include 'file.php';
?>

Function Local Scope

If you wish to access a global variable from within a function, you have to use the global keyword to tell the function that it should use the variable from the global scope instead of the function's own local scope.

<?php
function bar() {
    global $foo;

    echo $foo;
}

$foo = 1;
bar();
?>

Static Variables

<?php

function bar2() {
    static $i=0;
    return ++$i;
}

echo bar2()."<br>\n";

echo bar2()."<br>\n";
?>

Output

1
2

Loading ...

Related Results :

  1. Variable Scope
Note :
  • Related Posts are generally User Blog posts.
  • or Other tutorials from other networks of w3clan.com.
  • Any registered user can create related posts based on search term tags.

About the Author