|
|
|
Example: global scope and function scope
<?php $a = 1; # Global var a print("Main: a = " . $a . "\n"); f( ); print("Main: a = " . $a . "\n"); function f( ) { print("f before: a = " . $a . "\n"); # Function scoped var a -- error !! $a = 4444; # Define function scoped var a print("f before: a = " . $a . "\n"); # Function scoped var a -- no error } ?> |
Output:
Main: a = 1 PHP Notice: Undefined variable: a in scoping1.php on line 11 f before: a = <---- this a has not be created ! f before: a = 4444 Main: a = 1 |
How to run the program:
|
|
<?php $a = 1; # Global a print("Main: a = " . $a . "\n"); f($a); print("Main: a = " . $a . "\n"); /* ============================================================ function f( ) ============================================================ */ function f( ) { global $a; # ******** a will now access a global variable print("f before: a = " . $a . "\n"); # Uses global scoped var a !!! $a = 4444; print("f after: a = " . $a . "\n"); # Uses global scoped var a !!! } print("Main: a = " . $a . "\n"); ?> |
Output:
Main: a = 1 f before: a = 1 f before: a = 4444 Main: a = 4444 <-- Global variable is updated ! |
How to run the program:
|