3v4l.org

run code in 300+ PHP versions simultaneously
<?php class OrderItem { public int $order_id; public string $sku; public int $quantity; } class OrderItems { static function get(int $order_id):array { static $times = 0; if ( 0 !== $times ) { trigger_error('If this happens then the second call to callAndSet() evaluated the closure again.'); $times = 1; } // Simulating a two item order $item = new OrderItem(); $item->order_id = $order_id; $item->sku = 'ABC-123'; $item->quantity = 12; $item2 = new OrderItem(); $item2->order_id = $order_id; $item2->sku = 'XYZ-987'; $item2->quantity = 5; return [$item,$item2]; } } function callAndSet(mixed &$lazy) { return $lazy instanceof Closure ? $lazy = $lazy() : $lazy; } class Order { public int $order_id; public Closure|array $order_items; function __construct(int $order_id) { $this->order_id = $order_id; $this->order_items = fn() => OrderItems::get($order_id); } } $order = new Order(123); foreach( callAndSet($order->order_items) as $order_item) { printf("%d of %s\n", $order_item->quantity, $order_item->sku); } echo "---\n"; foreach( callAndSet($order->order_items) as $order_item) { printf("%d of %s\n", $order_item->quantity, $order_item->sku); } echo "---\n"; foreach( $order->order_items as $order_item) { printf("%d of %s\n", $order_item->quantity, $order_item->sku); }
Output for 8.0.8, 8.1.10 - 8.1.27, 8.2.10 - 8.2.17, 8.3.0 - 8.3.4
12 of ABC-123 5 of XYZ-987 --- 12 of ABC-123 5 of XYZ-987 --- 12 of ABC-123 5 of XYZ-987
Output for 7.4.19 - 7.4.30
Parse error: syntax error, unexpected '|', expecting variable (T_VARIABLE) in /in/7rs3N on line 35
Process exited with code 255.

preferences:
68 ms | 401 KiB | 27 Q