php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #75117 yield-by-reference in method class
Submitted: 2017-08-25 04:59 UTC Modified: 2017-08-25 08:02 UTC
From: alditis at gmail dot com Assigned:
Status: Not a bug Package: Scripting Engine problem
PHP Version: 7.1.8 OS: Ubuntu 16.04
Private report: No CVE-ID: None
View Add Comment Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
You can add a comment by following this link or if you reported this bug, you can edit this bug over here.
(description)
Block user comment
Status: Assign to:
Package:
Bug Type:
Summary:
From: alditis at gmail dot com
New email:
PHP Version: OS:

 

 [2017-08-25 04:59 UTC] alditis at gmail dot com
Description:
------------
yield-by-reference in the class method not working I how expected.



Test script:
---------------
class Test
{
    public $data = [];

    function __construct($data){
        $this->data = $data;
    }

    function &getIterator($d) {
        $this->data = $d;
        foreach ($d as $key => $value) {
            yield $key => $value;
        }
    }

    function printData()
    {
        foreach ($this->data as $key => $value) {
            echo($key . ':' . $value . PHP_EOL);
        }
    }
}

$data = array('one'=>'Curly', 'two'=>'Larry', 'three'=>'Moe');
$t = new Test($data);

foreach ($t->getIterator($data) as $key => &$value) {
    $value = strtoupper($value);
}

$t->printData();

Expected result:
----------------
I expected names in uppercase:

one:CURLY
two:LARRY
three:MOE

Actual result:
--------------
$t->printData() of the test script display:

one:Curly
two:Larry
three:Moe

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2017-08-25 08:02 UTC] requinix@php.net
-Status: Open +Status: Not a bug
 [2017-08-25 08:02 UTC] requinix@php.net
If you want $value to alter $data then you need references at every step between them. That's three more &s.

Your code got a bit messy after experimenting. Try https://3v4l.org/fiVkl
 [2017-08-26 01:06 UTC] alditis at gmail dot com
I added some changes. Now work it's. Thanks for the suggestions:

https://3v4l.org/oY8Iv
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Fri Mar 29 13:01:29 2024 UTC