| 1400 | class IterationDemo |
| 1401 | { |
| 1402 | public function demo(): void |
| 1403 | { |
| 1404 | $src = new ScaffoldingIteration(); |
| 1405 | |
| 1406 | // From method |
| 1407 | foreach ($src->allPens() as $pen) { |
| 1408 | $pen->write(); // list<Pen> → Pen |
| 1409 | } |
| 1410 | |
| 1411 | // From property |
| 1412 | foreach ($src->batch as $pen) { |
| 1413 | $pen->write(); |
| 1414 | } |
| 1415 | |
| 1416 | // Key types |
| 1417 | foreach ($src->crossRef() as $pen => $pencil) { |
| 1418 | $pen->write(); // Pen (key type) |
| 1419 | $pencil->sketch(); // Pencil (value type) |
| 1420 | } |
| 1421 | |
| 1422 | // WeakMap keys |
| 1423 | /** @var \WeakMap<Pen, Pencil> $mapping */ |
| 1424 | $mapping = new \WeakMap(); |
| 1425 | foreach ($mapping as $pen => $pencil) { |
| 1426 | $pen->write(); // key: Pen |
| 1427 | $pencil->sketch(); // value: Pencil |
| 1428 | } |
| 1429 | |
| 1430 | // Destructuring |
| 1431 | [$first, $second] = $src->allPens(); |
| 1432 | $first->write(); // destructured element type |
| 1433 | |
| 1434 | // Foreach destructuring |
| 1435 | /** @var array<int, array{string, int}> $rows */ |
| 1436 | $rows = [['Alice', 30], ['Bob', 25]]; |
| 1437 | foreach ($rows as [$name, $age]) { |
| 1438 | strlen($name); // string from positional shape |
| 1439 | abs($age); // int from positional shape |
| 1440 | } |
| 1441 | |
| 1442 | // Foreach keyed shape destructuring |
| 1443 | /** @var array<int, array{tool: Pen, count: int}> $inv */ |
| 1444 | $inv = []; |
| 1445 | foreach ($inv as ['tool' => $tool, 'count' => $count]) { |
| 1446 | $tool->write(); // Pen from keyed shape |
| 1447 | abs($count); // int from keyed shape |
| 1448 | } |
| 1449 | |
| 1450 | // Nested destructuring |
| 1451 | /** @var array{string, array{Pen, Pencil}} $nested */ |
| 1452 | $nested = ['label', [new Pen(), new Pencil()]]; |
| 1453 | [$label, [$nestedPen, $nestedPencil]] = $nested; |
| 1454 | strlen($label); // string from outer position 0 |
| 1455 | $nestedPen->write(); // Pen from inner position 0 |
| 1456 | $nestedPencil->sketch(); // Pencil from inner position 1 |
| 1457 | } |
| 1458 | } |
| 1459 | |