Bug #78970 [Opn->Ver]: Compact can't resolve outer scoped variables using short closures
| From: | nikic@php.net | Date: | Mon, 16 Dec 2019 13:52:14 +0000 |
| Subject: | Bug #78970 [Opn->Ver]: Compact can't resolve outer scoped variables using short closures | ||
| References: | 1 | Groups: | php.bugs |
| Request: | Send a blank email to php-bugs+get-224341@lists.php.net to get a copy of this message | ||
Edit report at https://bugs.php.net/bug.php?id=78970&edit=1
ID: 78970
Updated by: nikic@php.net
Reported by: stanislav dot goldmann at gmail dot com
Summary: Compact can't resolve outer scoped variables using
short closures
-Status: Open
+Status: Verified
Type: Bug
Package: Arrays related
Operating System: Linux/Any
PHP Version: 7.4.0
Block user comment: N
Private report: N
New Comment:
Due to lack of varvar support in arrow functions. Not going to be entirely simple.
Previous Comments:
------------------------------------------------------------------------
[2019-12-16 13:37:14] stanislav dot goldmann at gmail dot com
Description:
------------
In the proposal of short closures (https://wiki.php.net/rfc/arrow_functions_v2) 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) {
[0]=>
array(3) {
["name"]=>
string(3) "foo"
["value"]=>
string(3) "bar"
}
}
Actual result:
--------------
// Notice: compact(): Undefined variable: name
array(1) {
[0]=>
array(1) {
["value"]=>
string(3) "bar"
}
}
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=78970&edit=1