Sunday, July 5, 2009

Variable scope in functions

As mentioned already, variables declared outside of functions and classes are considered "global" - generally available to the script. However, as functions are independent blocks, their variables are self-contained and do not affect variables in the main script. In the same way, variables from the main script are not implicitly made available inside functions. Take a look at this example script:
function foo() {
$bar = "wombat";
}

$bar = "baz";
foo();
print $bar;
?>

Execution of the script starts at the $bar = "baz" line, and then calls the foo() function. Now, as you can see, foo() sets $bar to "wombat", then returns control to the main script where $bar is printed out. Consider for a moment what you think that script will do, taking into account what I have just said regarding variable scope in functions.

There are, overall, three possibilities:

1.

The script will print "baz"
2.

The script will print "wombat"
3.

The script will print nothing

Possibility one would be the case if the $bar variable was set outside of the function, foo() was called and set its own, local version of $bar, which was deleted once the function ended, leaving the original $bar in place.

Possibility two would be the case if the $bar variable was set outside of the function, foo() was called, and changed the global copy of $bar, therefore printing out the new value once control returns to the main script.

Possibility three would be the case if variables are lost in between function calls.

It is quite simple to discount the third possibility - variables declared globally, that is, outside of functions, remain in the global scope, no matter what functions you call.

The second possibility would mean that variables declared globally are automatically made available inside functions, which we know is not the case. Therefore, the first possibility is in fact correct - foo() is called, and, having no knowledge that a $bar variable exists in the global scope, creates a $bar variable in its local scope. Once the function ends, all local scopes are tossed away, leaving the original $bar variable intact.

For many this procedure is second nature, however it does take a little getting used to if you are new to programming, which is why I have gone into so much depth. This explicit level of scope is something you will find is particularly important once you go beyond simple scripts.

No comments:

Post a Comment