<?php
class Queue
{
private $queue = [];
public function add($var)
{
$this->queue[] = $var;
}
public function take(): \Generator
{
while($var = array_shift($this->queue)) {
if($var instanceof Queue) {
yield from $var->take();
} else {
yield $var;
}
}
}
}
$subQueue = new Queue();
$subQueue->add('A');
$subQueue->add('B');
$subQueue->add('C');
$queue = new Queue();
$queue->add('a');
$queue->add('b');
$queue->add('c');
$queue->add($subQueue);
$queue->add('d');
foreach($queue->take() as $index => $item) {
echo $index;
if($index === 1) {
$queue->add('hello');
}
var_dump($item);
}
- Output for 7.0.0 - 7.0.20, 7.1.0 - 7.1.25, 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.33, 8.2.0 - 8.2.29, 8.3.0 - 8.3.26, 8.4.1 - 8.4.13
- 0string(1) "a"
1string(1) "b"
2string(1) "c"
0string(1) "A"
1string(1) "B"
2string(1) "C"
3string(1) "d"
4string(5) "hello"
5string(5) "hello"
- Output for 5.6.0 - 5.6.27
- Parse error: syntax error, unexpected ':', expecting ';' or '{' in /in/sIpXu on line 10
Process exited with code 255.
preferences:
42.84 ms | 407 KiB | 5 Q