Forum Moderators: coopster

Message Too Old, No Replies

Lack of variable scoping

How to deal with it?

         

tata668

3:50 am on Mar 1, 2005 (gmt 0)

10+ Year Member



I think the lack of variable scoping is the weakest PHP point.
The fact that you can easily overwrite a variable without knowing it.

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.

ironik

4:04 am on Mar 1, 2005 (gmt 0)

10+ Year Member



Yes, its by design. Loops in php don't have their own scope like classes and functions.

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.

tata668

3:52 pm on Mar 1, 2005 (gmt 0)

10+ Year Member



I don't think it would be pleasant to use if(!isset($aVar)) each time you use a variable...

But thanks for the reply...

jollymcfats

5:19 pm on Mar 1, 2005 (gmt 0)

10+ Year Member



In PHP I do three things to stay out of trouble:
  1. Don't reuse variable names within in a function
  2. Run at maximum warning level to catch uninitialized variable access
  3. Try to never include() code from within a function
The last is somewhat subtle; if the included file defines global variables in the body of the file, their scope won't be global- they get scoped to the function that included the file. This usually bites me when loading a class that uses global variables to emulate class variables or share data.