<?php declare(strict_types=1); /** @template-covariant T */ class Store { /** @param T $value */ public function __construct(private $value) { } /** @return T */ public function getValue() { return $this->value; } } /** @template-covariant T */ class LazyValue { /** @var Store<T>|null */ private ?Store $store = null; /** @param Closure(): T $callable */ public function __construct(private Closure $callable) { } /** @return T */ public function getValue() { $store = $this->store ??= $this->doGetStore(); return $store->getValue(); } /** @return Store<T> */ private function doGetStore(): Store { $callable = $this->callable; $value = $callable(); return new Store($value); } } //------------------------ using it --------------------- function slow(): int { echo 'Doing slow calculation once'; return random_int(1, 42); } $lazy = new LazyValue(fn() => slow()); $lazy->getValue(); // prints: 'Doing slow calculation once', returns 'int' $lazy->getValue(); // does not print anything, only retuns 'int'
You have javascript disabled. You will not be able to edit any code.