开发者

PHP: What's the difference between static variable inside a for loop and a non-static variable outside the for loop?

For example, what's the difference between

$foobar = 0
for ($i=0; $i<20; $i++) {
    //do something using $foobar
    $foobar++;
}

and

for ($i=0; $i<20; $i++) {
    static $foobar = 0
    //do something using $foobar
    $foobar++;
}

???

Both of the above examples have diffe开发者_运维技巧rent results than from the following:

for ($i=0; $i<20; $i++) {
    $foobar = 0
    //do something using $foobar
    $foobar++;
}

All three variations have a different outcome. I understand that in the first of the three examples the value of the $foobar variable gets larger and larger and that in the third example the value of the $foobar variable gets reset during each loop. I'm not sure what's going on with the example using the static $foobar variable. It would seem that the first two examples should behave the same in the portion of the for loop where $foobar is used, but that is not the case for me.

For reference, here's my actual code (the algorithm is not complete yet). I've marked the for() loop that has me thinking about this topic:

function combine($charArr, $k) {

    $currentsize = sizeof($charArr);
    static $combs = array();
    static $originalsize = "unset";
    if ($originalsize === "unset") $originalsize = $currentsize;
    static $firstcall = true;

    if ($originalsize >= $k) {

        $comb = '';
        if ($firstcall === true) { 
            for ($i = $originalsize-$k; $i < $originalsize; $i++) {
                $comb .= $charArr[$i];
            }
            $combs[] = $comb; 
            $firstcall = false; 
        }
        if ($currentsize > $k) { 

            $comb = ''; //reset
            for ($i=0; $i<$k; $i++) { 
                $comb .= $charArr[$i];
            }
            $combs[] = $comb;

            //########### THE FOR LOOP IN QUESTION ###########              
            for ($i = $k-1; $i >= 0; $i--) { 
            static $range_adj = 0;
                for ( $j = $i+1; $j < $currentsize-$range_adj; $j++ ) { 
                    if ( !($i == 0 and $j == $currentsize-$range_adj-1) ) { 
                        $comb = substr_replace($comb, $charArr[$j], $i, 1); 
                        $combs[] = $comb;
                    }
                }
                $range_adj++;
            }
            if ($currentsize-1 > $k) { 
                array_splice($charArr, 0, 1); 
                combine($charArr, $k); 
            }
        }
        $output = array_values( $combs );
        unset($combs);
        return $output;
    }
    else {
        return false;
    }
}

If I remove the $range_adj variable from for loop and place it right before the said for loop as a none-static variable, then the result of my function is not the same. Here's what the modified for loop would look like:

            $range_adj = 0;
            for ($i = $k-1; $i >= 0; $i--) { 
                for ( $j = $i+1; $j < $currentsize-$range_adj; $j++ ) { 
                    if ( !($i == 0 and $j == $currentsize-$range_adj-1) ) { 
                        $comb = substr_replace($comb, $charArr[$j], $i, 1); 
                        $combs[] = $comb;
                    }
                }
                $range_adj++;
            }

The fact that I get two different outcomes leads me to believe that something is different with each method, because if the two methods produced identical results, then the outcome of my function would be the same in both scenarios, which is not the case when I test these scenarios. Why am I getting two results? Test my function out with both methods of the for loop implemented and you will also get varying results.

For your convenience, here's the original method:

            for ($i = $k-1; $i >= 0; $i--) { 
                static $range_adj = 0;
                for ( $j = $i+1; $j < $currentsize-$range_adj; $j++ ) { 
                    if ( !($i == 0 and $j == $currentsize-$range_adj-1) ) { 
                        $comb = substr_replace($comb, $charArr[$j], $i, 1); 
                        $combs[] = $comb;
                    }
                }
                $range_adj++;
            }

???

It seems to me that the results should be exactly the same, but they are not. If you run my function, you will notice that you get a different result with each method of the for loop.


The first and second loops appear to do the same thing. This is because, as with any other statically-initialized variable, static means you only initialize it once. It retains its value as you try to access it again. You'll find that the static $foobar will still exist outside the scope of the loop wherever you declare/initialize it; this is due to the nature of PHP and has nothing to do with the static variable.

The difference is made clear only when you attempt to access $foobar before the loop: it won't be declared yet in the second snippet because you only create it within the loop, so you may get an undefined-variable notice.


static $foobar = 0;
initializing once, other execute of static $foobar = 0 not do anything with $foobar variable


Above two prog have same output, but your last prog have variable which is reset during each loop. when you use "Static" key word for any variable initialization then It retains untill you not destroy it.. or not destroy your program session.


You can use static in this fashion to prevent a variable from being reinitialized inside a loop.

in the first iteration if the static variable is not initialize then it would create it and keep it within the outer context, on every other iteration PHP Would just skip it as its already been initialized.

Both results prevail the same: http://codepad.org/evilks4R

The reason why it differs in your function is that your function is recursive which means the function combine calls combine from within itself, when taking out the static keyword on the second call of combine, the variable is being reinitialized thus making the results differ.

using the static keyword allows you to pass the arguments to the second call with there values that was produced in the third value.

here's an example of passing static members to the latter passes of a function call: http://codepad.org/gChjx7Om

if you had done:

$foo_bar = 0;
for(.....)

this would be within a function so that $foo_bar would get reset to 0 every time the function was called, therefore overwriting the last calls calculations.

if you moved the $foo_bar outside the function, and then where needed in the function you added:

global $foo_bar

you would have the same results.

http://www.cprogramming.com/tutorial/statickeyword.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜