Cannot open file (/home/u0059333506/public_html/wordpress/wp-content/backup/.htaccess)Cannot write to file (/home/u0059333506/public_html/wordpress/wp-content/backup/.htaccess) Scope and foreach loops « Hanno’s Coding Log

Hanno’s Coding Log: software development, geek stuff

Scope and foreach loops

One of these misunderstandings: I always thought foreach loops would create a temporary variable for the current element that would mask any variable with the same name in the current scope.

Obviously that is not the case, as I discovered when I tried to find a bug in Simple Tagging’s STP_RelatedPosts() function.

First I thought this was a PHP-only behavior… But see the following PHP and Python examples:

function localFunction(){
    global $id;
    $keys = array(1, 2, 3, 4);
    foreach($keys as $id){
        echo "local: ", $id, "\n";
    }
}
$id = 1;
localFunction();
echo "global: ", $id;
id = 1
def localFunction():
    global id
    keys = [1, 2, 3, 4]
    for id in keys:
        print "local: %i" % id
 
localFunction()
print "global: %i" % id

will print:

local: 1
local: 2
local: 3
local: 4
global: 4
  • Digg
  • del.icio.us
  • MisterWong
  • Technorati
  • StumbleUpon
  • Yigg

Related posts

You can follow any responses to this entry through the RSS 2.0 feed.

Stoppt die Vorratsdatenspeicherung! Jetzt klicken & handeln!Willst du auch bei der Aktion teilnehmen? Hier findest du alle relevanten Infos und Materialien: