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.31, 8.2.10 - 8.2.27, 8.3.0 - 8.3.4, 8.3.6 - 8.3.15, 8.4.1 - 8.4.2
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 8.3.5
Warning: PHP Startup: Unable to load dynamic library 'sodium.so' (tried: /usr/lib/php/8.3.5/modules/sodium.so (libsodium.so.23: cannot open shared object file: No such file or directory), /usr/lib/php/8.3.5/modules/sodium.so.so (/usr/lib/php/8.3.5/modules/sodium.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 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:
59.63 ms | 408 KiB | 5 Q