php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #48292 value in anonymous functions isn't passed by reference
Submitted: 2009-05-15 11:16 UTC Modified: 2009-05-15 20:26 UTC
Votes:1
Avg. Score:2.0 ± 0.0
Reproduced:1 of 1 (100.0%)
Same Version:1 (100.0%)
Same OS:1 (100.0%)
From: php at hotblocks dot nl Assigned:
Status: Not a bug Package: Scripting Engine problem
PHP Version: 5.3.0RC2 OS: Windows XP
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: php at hotblocks dot nl
New email:
PHP Version: OS:

 

 [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
)

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2009-05-15 20:26 UTC] jani@php.net
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.


 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Thu Dec 04 20:00:01 2025 UTC