|  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #78970 Compact can't resolve outer scoped variables using short closures
Submitted: 2019-12-16 13:37 UTC Modified: 2019-12-16 13:52 UTC
Avg. Score:3.8 ± 1.0
Reproduced:4 of 5 (80.0%)
Same Version:2 (50.0%)
Same OS:3 (75.0%)
From: stanislav dot goldmann at gmail dot com Assigned:
Status: Verified Package: Arrays related
PHP Version: 7.4.0 OS: Linux/Any
Private report: No CVE-ID: None
Have you experienced this issue?
Rate the importance of this bug to you:

 [2019-12-16 13:37 UTC] stanislav dot goldmann at gmail dot com
In the proposal of short closures ( the following is stated:

"When a variable used in the expression is defined in the parent scope it will be implicitly captured by-value."

With this example:

$y = 1;

$fn1 = fn($x) => $x + $y;

$fn2 = function ($x) use ($y) {
    return $x + $y;

These two behave exactly the same, as expected.
However compact doesn't behave that way, as it doesn't recognize a variable from outer scope until it is explicitly called.

Test script:
$name = 'foo';
$array = ['bar'];

$failing = fn($value) => compact('name', 'value');
$working = fn($value) => compact('name', 'value') + [$name];

var_dump(array_map($failing, $array));
var_dump(array_map($working, $array));

Expected result:
Short closures using compact should resolve outer scoped variables and behave like "long" closures using an use statement.

fn($value) => compact('name', 'value')

should work just like

function($value) use ($name) {
    return compact('name', 'value');

And return the following

array(1) {
  array(3) {
    string(3) "foo"
    string(3) "bar"

Actual result:
// Notice: compact(): Undefined variable: name

array(1) {
  array(1) {
    string(3) "bar"


Add a Patch

Pull Requests

Add a Pull Request


AllCommentsChangesGit/SVN commitsRelated reports
 [2019-12-16 13:52 UTC]
-Status: Open +Status: Verified
 [2019-12-16 13:52 UTC]
Due to lack of varvar support in arrow functions. Not going to be entirely simple.
PHP Copyright © 2001-2023 The PHP Group
All rights reserved.
Last updated: Sun Jan 29 02:03:43 2023 UTC