Reputation: 327
Given the following code
public static function &generate($arr)
{
foreach ($arr as $key => $value) {
yield $key => $value;
}
}
This static method should yield $key => $value by ref on each array iteration
Then I use the static method in another class:
$questions = $request->questions;
foreach (self::generate($questions) as &$question) {
$question['label'] = json_encode($question['label']);
... other code
}
unset($question);
die(var_dump($questions[0]['label']));
I should have a json encoded string but I always have an array, I don't understand why.
questions
attribute in the $request var doesn't exist, it is returned by the magic method __get
(questions
is inside of an array so the value is returned by __get)$questions
to my foreach, it works and I have my json encoded stringUpvotes: 4
Views: 390
Reputation: 212452
You need to ensure pass-by-reference "all the way through"
public static function &generate(&$arr)
{
foreach ($arr as $key => &$value) {
yield $key => $value;
}
}
for both $arr
and $value
Upvotes: 2