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;
echo "global: ", $id;
id = 1
def localFunction():
    global id
    keys = [1, 2, 3, 4]
    for id in keys:
        print "local: %i" % id
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: