发电机参考

时间:2017-08-22 06:06:06

标签: generator php-7.1

我通过以下两种方式测试发电机:

N°1:有效

<?php

$value = 3;

function &gen_reference() {
    global $value;

    while ($value > 0) {
        yield $value;
    }
}

foreach (gen_reference() as &$number) {
    --$number;
}

echo($value . PHP_EOL); // 0

N°2:显示不是我想要的。

<?php

class Test
{

    public $data = [];

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

    function &getIterator() {
        foreach ($this->data 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() as $key => &$value) {
    $value = strtoupper($value); // Does not update $this->data
}

$t->printData();

显示:

one:Curly
two:Larry
three:Moe

我期待:

one:CURLY
two:LARRY
three:MOE

有任何更正或建议吗?

1 个答案:

答案 0 :(得分:0)

添加&amp;在&amp; getIterator函数中使用$ value来保持引用:

function &getIterator() {
    foreach ($this->data as $key => &$value) { // Here add & to $value
        yield $key => $value;
    }
}

代码完成:

class Test
{

    public $data = [];

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

    function &getIterator() {
        foreach ($this->data as $key => &$value) { // Here add & to $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() as $key => &$value) {
    $value = strtoupper($value); // Does not update $this->data
}

$t->printData();