php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #68075 Functions defined in closures may not be called before definition
Submitted: 2014-09-22 17:26 UTC Modified: 2014-09-22 17:49 UTC
From: fieryprophet at yahoo dot com Assigned:
Status: Not a bug Package: Scripting Engine problem
PHP Version: Irrelevant OS: All
Private report: No CVE-ID: None
View Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
If you reported this bug, you can edit this bug over here.
(description)
Block user comment
Status: Assign to:
Package:
Bug Type:
Summary:
From: fieryprophet at yahoo dot com
New email:
PHP Version: OS:

 

 [2014-09-22 17:26 UTC] fieryprophet at yahoo dot com
Description:
------------
PHP allows calls to functions that have not yet been defined as long as they are defined at some point in the script.

However, this behavior is not consistent when applied to Closures, as function calls within a closure will fail if they are not defined before they are made even if the function definition is contained within the same closure.

If the function in question is defined outside of a closure but after the closure is created, the script will also proceed as expected.

Test script:
---------------
test();

function test(){
    echo "Test works\r\n";
}

//output: Test works

$closure = function(){
    closure_test();
    
    function closure_test(){
        echo "Closure test works\r\n";
    }
};
$closure();

//expected output: Closure test works
//actual output: Fatal error: Call to undefined function closure_test()

Expected result:
----------------
Test works
Closure test works

Actual result:
--------------
Test works
Fatal error: Call to undefined function closure_test()

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2014-09-22 17:49 UTC] requinix@php.net
-Status: Open +Status: Not a bug
 [2014-09-22 17:49 UTC] requinix@php.net
> PHP allows calls to functions that have not yet been defined as long as they
> are defined at some point in the script.
That's only part of the rule. The rest is "...and are not defined conditionally."
http://php.net/manual/en/functions.user-defined.php

Anything conditional does not (and cannot) get that kind of special "look ahead" treatment and will be evaluated like any other statement; same thing happens in a closure, regular function, if, switch, etc.
 
PHP Copyright © 2001-2026 The PHP Group
All rights reserved.
Last updated: Wed Oct 07 00:00:02 2026 UTC