#37046 [Opn]: foreach breaks static scope

From: Date: Wed, 12 Apr 2006 00:08:05 +0000
Subject: #37046 [Opn]: foreach breaks static scope
References: 1  Groups: php.bugs 
Request: Send a blank email to php-bugs+get-95644@lists.php.net to get a copy of this message
ID: 37046 User updated by: karoly at negyesi dot net Reported By: karoly at negyesi dot net Status: Open Bug Type: Scripting Engine problem Operating System: Linux PHP Version: 5.1.2 New Comment: I thought best is if I provide one script... <?php function s($key) { static $storage = array('a' => array('x', 'y')); return $storage[$key]; } function s1($key) { static $storage = array('a' => array('x', 'y')); return (array)$storage[$key]; } function s2() { static $storage = array('x', 'y'); return $storage; } function invoke($op, $st) { foreach ($st('a') as $k => $function) { echo "$op $k\n"; $function($op, $st); } } function x($op, $st) { if ($op == 'op1') invoke('op2', $st); } function y() { } invoke('op1', 's'); echo "\n"; invoke('op1', 's1'); echo "\n"; invoke('op1', 's2'); ?> You get op1 0 op2 0 op2 1 op1 0 op2 0 op2 1 op1 1 op1 0 op2 0 op2 1 op1 1 if this is not a bug then why they differ? Previous Comments: ------------------------------------------------------------------------ [2006-04-11 23:01:21] karoly at negyesi dot net I think this is still a bug. See my first comment -- that differs very slightly and yet it works. ------------------------------------------------------------------------ [2006-04-11 22:26:21] tony2001@php.net You are using the same array in nested foreach() loops. Apparently the array pointer is moved is the parent loop, which affect the nested one. No bug here. ------------------------------------------------------------------------ [2006-04-11 21:52:31] karoly at negyesi dot net function storage() { static $storage = array('x', 'y'); return $storage; } works as well. ------------------------------------------------------------------------ [2006-04-11 21:43:54] karoly at negyesi dot net Description: ------------ foreach changes the array pointer of a static in another function. Reproduce code: --------------- <?php function storage($key) { // uncomment the following line to see the expected result // return array('x', 'y'); static $storage = array('a' => array('x', 'y')); return $storage[$key]; } function invoke($op) { foreach (storage('a') as $k => $function) { echo "$op $k\n"; $function($op); } } function x($op) { if ($op == 'op1') invoke('op2'); } function y() { } invoke('op1'); Expected result: ---------------- op1 0 op2 0 op2 1 op1 1 Actual result: -------------- op1 0 op2 0 op2 1 ------------------------------------------------------------------------ -- Edit this bug report at http://bugs.php.net/?id=37046&edit=1

« previous php.bugs (#95644) next »