Variable scope

March 25th, 2005. Tagged: PHP certification

The certification book goes on with the calc_weeks example:

< ?php
function calc_weeks() {
$years += 10;
return $years * 52;
}
$years = 28;
echo calc_weeks();
?>

Exactly as the guide says, the $years var in the function won't get the 28 value, it will get a null instead. But then the guide says that the result of the function will be 0, while it is going to be 520.

Simply put the variables have visibility only in the brackets where they reside. That is, unless you global-ize them. Like:
< ?php
function calc_weeks() {
global $years;
$years += 10;
return $years * 52;
}
$years = 28;
echo calc_weeks();
?>

A different approach is to use a global variable by the $GLOBALS superglobal array. The example above will translate to
< ?php
function calc_weeks() {
$GLOBALS['years'] += 10;
return $GLOBALS['years'] * 52;
}
$years = 28;
echo calc_weeks();
?>

Tell your friends about this post: Facebook, Twitter, Google+

Sorry, comments disabled and hidden due to excessive spam. Working on restoring the existing comments...

Meanwhile, hit me up on twitter @stoyanstefanov