2017-08-22 70 views
0

我通過兩種方式參考測試發生器:發生器通過引用

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 

任何修正或建議?

回答

0

添加&至$值& getIterator功能保持引用:

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();