4 ms·
>> This would require a yield to syntax, which doesn't exist. There is however the 'yield from' statement.
by Amakanski 1y ago
>> This would require a yield to syntax, which doesn't exist.
There is however the 'yield from' statement.
- zelphirkalt 1y agoThis means, that most likely the keyword will not be "yield". PHP is not known for keeping a low number of keywords. Rather they introduce new ones, to tack on things to the language, like one can see in the implementation of anonymous functions, where one needs to use "use" explicitly, instead of the language having the semantics that most other languages have for lambdas. Which immediately turns in to a source for nullability errors.
- djxfade 1y agoThat's not totally correct. PHP has a "short function" syntax for that specific use case, it automatically captures data without the 'use' statement. $a = 5; $b = fn ($c) => $a * $b; print($b(2)); // 10 print($b(4)); // 20
- deleted 1y ago[deleted]
- dotancohen 1y agoThis "arrow function" syntax was introduced much later, though.
- Cyykratahk 1y agoI'd use `yield from` more if I didn't have to re-index arrays before yielding from them: function numbers() { yield from [1,2,3]; yield from [4,5,6]; }; foreach (numbers() as $k => $v) { echo "$k => $v\n"; } 0 => 1 1 => 2 2 => 3 0 => 4 1 => 5 2 => 6
- bvrmn 1y agoPHP generators/iterators is a hot mess. I don't know any other language which forces iterators to output a key for `foreach(... as $key => ...)`.
- jw1224 1y agoPHP doesn’t force keys... You can omit the key and simply write `foreach($items as $value)`
- bvrmn 1y agoBTW: https://www.php.net/manual/en/iterator.key.php https://www.php.net/manual/en/iterator.key.php It's literally in the interface.
- jw1224 1y agoI’m not sure I follow, what exactly is your complaint? The Iterator interface is described as: > Interface for external iterators or objects that can be iterated themselves internally Note “external iterators or objects”. The Iterator interface is not exactly everyday PHP, it’s a specialist utility for making classes iterable so they can be accessed like arrays. Most developers will rarely use it directly, and it’s not being used in the parent comment’s example either. Iterating over something requires knowing where you are in the sequence, so of course you would need to implement a method to get the current position of the iteration.
- bvrmn 1y ago> Iterating over something requires knowing where you are in the sequence, so of course you would need to implement a method to get the current position of the iteration. No you don't. Other languages don't require it. There is no issue to get a position outside of iterator and it's more generic approach.
- 1y ago
- doekenorg 1y agoYes, there is! However, even if the `iterable` it was yielding from a different Generator, the "outer" generator would still be "running", which still makes it asymmetrical. `yield from` is mentioned in the other post on Generators, though.