|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2009-05-15 11:16 UTC] php at hotblocks dot nl
Description:
------------
PHP version 5.3.0-a3.
I think $f_source in the anonymous function passed to myForeach isn't passed by reference, even though the syntax is correct.
The problem appears when an anonymous function is passed to a global function in a method of a class. Within that anonymous (nameless) function the source of the myForeach can't be retrieved (only local and global can be retrieved), so I pass $list to the anonymous function as well. When I change a key or unset the member, it's not recorded back to the original $list.
Which makes me conclude $f_source is NOT passed by reference.
Reproduce code:
---------------
function myForeach( $f_source, $f_handler ) {
foreach ( $f_source AS $k => $v ) {
$f_handler($v, $k, $f_source);
}
}
class SecondClass {
public function __construct() {
$list = range('A', 'J');
myForeach($list, function($v, $k, &$f_source) {
if ( 'F' == $v ) {
$f_source[$k] = 'X';
unset($f_source[$k]);
$f_source[$k] = 'X';
}
});
print_r($list);
}
}
new SecondClass;
Expected result:
----------------
Array
(
[0] => A
[1] => B
[2] => C
[3] => D
[4] => E
[6] => G
[7] => H
[8] => I
[9] => J
)
Notice the [5] => F missing.
-OR-
Array
(
[0] => A
[1] => B
[2] => C
[3] => D
[4] => E
[5] => X
[6] => G
[7] => H
[8] => I
[9] => J
)
Actual result:
--------------
Array
(
[0] => A
[1] => B
[2] => C
[3] => D
[4] => E
[5] => F
[6] => G
[7] => H
[8] => I
[9] => J
)
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Thu Dec 04 20:00:01 2025 UTC |
Actually expected result is: Array ( [0] => A [1] => B [2] => C [3] => D [4] => E [6] => G [7] => H [8] => I [9] => J [5] => X ) And that you get when you fix your script like this: function myForeach( &$f_source, $f_handler ) { ie. Pass the array by reference. Otherwise you're modifying a copy.