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
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
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

Pull Requests

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-2025 The PHP Group
All rights reserved.
Last updated: Wed Jul 16 09:01:33 2025 UTC