|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2006-04-11 21:43 UTC] 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
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Tue Nov 11 16:00:01 2025 UTC |
function storage() { static $storage = array('x', 'y'); return $storage; } works as well.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?The simplified example: Reproduce code: --------------- <?php function s() { static $storage = array(array('x', 'y')); return $storage[0]; } foreach (s('a') as $k => $function) { echo "op1 $k\n"; if ($k == 0) { foreach (s('a') as $k => $function) { echo "op2 $k\n"; } } } ?> Expected result: ---------------- op1 0 op2 0 op2 1 op1 1 Actual result: -------------- op1 0 op2 0 op2 1 The bug is similar to bug #35106 (nested foreach fails when array variable has a reference), but has different reason.