php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #50814 Anonymous functions pull global variables from wrong scope
Submitted: 2010-01-21 15:14 UTC Modified: 2010-01-21 15:28 UTC
Votes:1
Avg. Score:5.0 ± 0.0
Reproduced:1 of 1 (100.0%)
Same Version:1 (100.0%)
Same OS:1 (100.0%)
From: kwilson at shuttlebox dot net Assigned:
Status: Not a bug Package: Unknown/Other Function
PHP Version: 5.3.1 OS: Linux
Private report: No CVE-ID: None
 [2010-01-21 15:14 UTC] kwilson at shuttlebox dot net
Description:
------------
If an anonymous function pulls a variable from the global scope using "global", and that function is passed to another scope, it pulls the variable from the scope where the function was created, not where it was executed.

Reproduce code:
---------------
<?php
    $variable = "first";
    
    $closure = function() {
        global $variable;
        
        echo $variable . "\n";
    };
    
    $closure();
    
    function test($closure)
    {
        $variable = "second";
        
        $closure();
    }
    
    test($closure);
?>

Expected result:
----------------
first
second

Actual result:
--------------
first
first

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2010-01-21 15:28 UTC] johannes@php.net
Thank you for taking the time to write to us, but this is not
a bug. Please double-check the documentation available at
http://www.php.net/manual/ and the instructions on how to report
a bug at http://bugs.php.net/how-to-report.php

global imports from the global scope, not the caller\'s or such.
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Sat Aug 02 03:00:02 2025 UTC