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); }

preferences:
28.9 ms | 402 KiB | 5 Q