note 125239 added to functions.arrow
| From: | dexen dot devries at gmail dot com | Date: | Mon, 03 Aug 2020 07:39:24 +0000 |
| Subject: | note 125239 added to functions.arrow | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-214922@lists.php.net to get a copy of this message | ||
Beware compact() not being able to access (import) variables from external scope (known in versions:
7.4.0, 7.4.8) (bug: https://bugs.php.net/bug.php?id=78970).
A workaround is available - use the variable directly; this will cause it to be imported into the
arrow function's namespace and make it available to the compact() too.
<?php
$aa = 111;
$accessing_variable_works = fn($bb) => [ $aa, $bb ];
$compact_is_broken = fn($bb) => compact('aa', 'bb');
$compact_can_work_with_workaround = fn($bb) => compact('aa', 'bb') +
['workaround' => $aa];
var_dump($accessing_variable_works(333));
var_dump($compact_is_broken(555));
var_dump($compact_can_work_with_workaround(777));
?>
result:
array(2) {
[0]=>
int(111)
[1]=>
int(333)
}
PHP Notice: compact(): Undefined variable: aa in /home/m/vlt/guitar/tlb/s/public_html/index.php on
line 9
array(1) {
["bb"]=>
int(555)
}
array(3) {
["aa"]=>
int(111)
["bb"]=>
int(777)
["workaround"]=>
int(111)
}
----
Server IP: 45.112.84.4
Probable Submitter: 103.51.166.36 (proxied: 188.47.75.214)
----
Manual Page -- http://php.net/manual/en/functions.arrow.php
Edit -- https://master.php.net/note/edit/125239
Del: integrated -- https://master.php.net/note/delete/125239/integrated
Del: useless -- https://master.php.net/note/delete/125239/useless
Del: bad code -- https://master.php.net/note/delete/125239/bad+code
Del: spam -- https://master.php.net/note/delete/125239/spam
Del: non-english -- https://master.php.net/note/delete/125239/non-english
Del: in docs -- https://master.php.net/note/delete/125239/in+docs
Del: other reasons-- https://master.php.net/note/delete/125239
Reject -- https://master.php.net/note/reject/125239
Search -- https://master.php.net/manage/user-notes.php