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










