note 129870 added to reflectionclass.newlazyghost

From: Date: Mon, 25 Nov 2024 13:11:16 +0000
Subject: note 129870 added to reflectionclass.newlazyghost
Groups: php.notes 
Request: Send a blank email to php-notes+get-221671@lists.php.net to get a copy of this message
Simple helper function that makes it easier to understand: <?php function createLazyGhost( string $class, ?callable $initializer = null, ?array $propertySetterCallables = null ): object { $reflection = new ReflectionClass($class); return $reflection->newLazyGhost(function (object $object) use ($initializer, $propertySetterCallables) { // Initialize via the main initializer if provided if ($initializer) { $initializer($object); } // Set properties using the callables if provided if ($propertySetterCallables) { foreach ($propertySetterCallables as $property => $callable) { if (is_callable($callable)) { $object->$property = $callable(); } } } }); } ?> This supports using either a main object initializer and/or property initializers. Here's an example, where generating order IDs and calculating totals is considered expensive, so we only do it when necessary: <?php class Order { public string $orderId = ''; public float $total = 0.0; } $initializer = function (Order $order) { $order->orderId = 'ORD12345'; }; $propertySetters = [ 'total' => fn() => 200.75, ]; // Lazy ghost with both an initializer and property callables $lazyOrder = createLazyGhost(Order::class, $initializer, $propertySetters); // We can now use $lazyOrder as normal, even though the properties haven't been calculated yet. // Do something that triggers initialization echo $lazyOrder->orderId . PHP_EOL; echo $lazyOrder->total . PHP_EOL; ?> ---- Server IP: 45.112.84.4 Probable Submitter: 80.90.5.137 (proxied: 86.27.197.94) ---- Manual Page -- https://php.net/manual/en/reflectionclass.newlazyghost.php Edit -- https://main.php.net/note/edit/129870 Del: integrated -- https://main.php.net/note/delete/129870/integrated Del: useless -- https://main.php.net/note/delete/129870/useless Del: bad code -- https://main.php.net/note/delete/129870/bad+code Del: spam -- https://main.php.net/note/delete/129870/spam Del: non-english -- https://main.php.net/note/delete/129870/non-english Del: in docs -- https://main.php.net/note/delete/129870/in+docs Del: other reasons-- https://main.php.net/note/delete/129870 Reject -- https://main.php.net/note/reject/129870 Search -- https://main.php.net/manage/user-notes.php

« previous php.notes (#221671) next »