Forum Moderators: coopster
Classes can be used to help scoping, but not always. Let's say I, by mistake, use $aVar like this:
$aVar = 1 ;
// lot of code here
foreach($anArray as $value)
{
$aVar = $value ;
}
echo $aVar ;
I would expect 1 here, but in fact $aVar will be equal to the last $value from the foreach loop.
How could I prevent this?
How is it possible to workaround this lack of scoping?
I know this is "by design" but I would be interested to know your tricks to help prevent errors.
Do a check on the variable before assigning to it:
$aVar = 1 ;
// lot of code here
foreach($anArray as $value)
{
// has the variable been set prior to the loop?
if (!isset($aVar))
{
// No, then assign the value
$aVar = $value ;
}
}
echo $aVar ;
To my knowledge you can't change scope, or prevent the variable being written... you just have to be careful.