Bug #79996 [Opn->Nab]: Reference trouble in closure

From: Date: Wed, 19 Aug 2020 12:42:28 +0000
Subject: Bug #79996 [Opn->Nab]: Reference trouble in closure
References: 1  Groups: php.bugs 
Request: Send a blank email to php-bugs+get-228673@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
 Updated by:         danack@php.net
 Reported by:        tropicano at ukr dot net
 Summary:            Reference trouble in closure
-Status:             Open
+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:

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.


Previous Comments:
------------------------------------------------------------------------
[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


Thread (5 messages)

« previous php.bugs (#228673) next »