Bug #79996 [Com]: Reference trouble in closure
| From: | tropicano at ukr dot net | Date: | Wed, 19 Aug 2020 14:11:04 +0000 |
| Subject: | Bug #79996 [Com]: Reference trouble in closure | ||
| References: | 1 | Groups: | php.bugs |
| Request: | Send a blank email to php-bugs+get-228676@lists.php.net to get a copy of this message | ||
Edit report at https://bugs.php.net/bug.php?id=79996&edit=1
ID: 79996
Comment by: tropicano at ukr dot net
Reported by: tropicano at ukr dot net
Summary: Reference trouble in closure
Status: Not a bug
Type: Bug
Package: *General Issues
Operating System: Windows 10
PHP Version: 7.4.9
Block user comment: N
Private report: N
New Comment:
Thanks!
Previous Comments:
------------------------------------------------------------------------
[2020-08-19 13:40:51] danack@php.net
Pretty sure your code is the equivalent of:
$x = 0;
$data = 1;
$foo = &$data;
$foo = &$x;
$foo = 40;
echo $data;
When a value is written to $foo, it is poiting to where $x is stored.
Which means that $data still has the original value it had, and was never modified.
------------------------------------------------------------------------
[2020-08-19 13:15:00] tropicano at ukr dot net
I known that it possible not good construction, my code is very hard to show bug.
But $data must be assigned value "2" or show notice/warning/error.
------------------------------------------------------------------------
[2020-08-19 12:42:28] danack@php.net
Pretty sure your code is working correctly, just not as you expect it to.
$data =& $x;
That line makes $data be a reference to the value stored in $x which was captured by value in
use ($x) . It breaks the reference to the value stored in $data = 1
I'd pretty strongly recommend not using references like this. Either use objects with clearer
semantics, or just pass in and return values. Trying to manage state with references like this is
confusing, as you're finding out.
------------------------------------------------------------------------
[2020-08-19 12:30:46] tropicano at ukr dot net
Description:
------------
Not correct result in closure function.
Please review and fix it.
Test script:
---------------
$x = 0;
function main($func, $func2)
{
return $func($func2);
}
function callback_main($func3)
{
$data = 1;
$func3($data);
return $data;
}
echo main('callback_main', function (&$data) use ($x)
{
$data =& $x;
$data = 2;
}
);
Expected result:
----------------
echo is: 1
Actual result:
--------------
must be: 2
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=79996&edit=1