一个简单的辅助函数,使理解更容易
<?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) {
if ($initializer) {
$initializer($object);
}
if ($propertySetterCallables) {
foreach ($propertySetterCallables as $property => $callable) {
if (is_callable($callable)) {
$object->$property = $callable();
}
}
}
});
}
?>
这支持使用主对象初始化器和/或属性初始化器。
这是一个示例,其中生成订单 ID 和计算总计被认为是昂贵的操作,因此我们只在必要时才执行。
<?php
class Order {
public string $orderId = '';
public float $total = 0.0;
}
$initializer = function (Order $order) {
$order->orderId = 'ORD12345';
};
$propertySetters = [
'total' => fn() => 200.75,
];
$lazyOrder = createLazyGhost(Order::class, $initializer, $propertySetters);
echo $lazyOrder->orderId . PHP_EOL;
echo $lazyOrder->total . PHP_EOL;
?>