3v4l.org

run code in 300+ PHP versions simultaneously
<?php interface ProductRepository { public function findReferenceBySku(string $sku): Product; public function findIdBySku(string $sku): int; } class Product { public function __construct( public int $id, ) { } } class ProductDatabaseRepository implements ProductRepository { public function findReferenceBySku(string $sku): Product { $id = $this->findIdBySku($sku); return $this->getProductReference($id); } private function getProductReference(int $id) { // check entity manager for existing object // and generate proxy if not found return new Product($id); } public function findIdBySku(string $sku): int { $this->queryDatabase(); return match($sku) { 'sku1' => 1, }; } protected function queryDatabase() { // note this method is not public var_dump('query database'); } } class ProductCachedRepository implements ProductRepository { private array $cachedIds = []; public function __construct( private ProductRepository $inner ) {} public function findReferenceBySku(string $sku): Product { // not able to delegate this logic directly to inner class // (loss of findIdBySku() overridden logic) //return $this->inner->findReferenceBySku($sku); // as well not able call decorated method with substitude this return $this->inner->findReferenceBySku(...)->call($this, $sku); } public function findIdBySku(string $sku): int { var_dump('check cache'); return $this->cachedIds[$sku] ??= $this->inner->findIdBySku($sku); } public function __call($name, $arguments) { // all not public methods of inner repository // which are not declared in current class // are delegated to inner repository return (fn() => $this->$name(...$arguments)) ->call($this->inner); } } $repository = (new ProductCachedRepository(new ProductDatabaseRepository())); var_dump('call1', $repository->findReferenceBySku('sku1')); var_dump('call2', $repository->findReferenceBySku('sku1')); // cache hit expected var_dump('call2', $repository->findReferenceBySku('sku1')); // cache hit expected
Output for git.master_jit, git.master
Warning: Cannot bind method ProductDatabaseRepository::findReferenceBySku() to object of class ProductCachedRepository in /in/CFE1u on line 67 Fatal error: Uncaught TypeError: ProductCachedRepository::findReferenceBySku(): Return value must be of type Product, null returned in /in/CFE1u:67 Stack trace: #0 /in/CFE1u(92): ProductCachedRepository->findReferenceBySku('sku1') #1 {main} thrown in /in/CFE1u on line 67
Process exited with code 255.

This tab shows result from various feature-branches currently under review by the php developers. Contact me to have additional branches featured.

Active branches

Archived branches

Once feature-branches are merged or declined, they are no longer available. Their functionality (when merged) can be viewed from the main output page


preferences:
48.09 ms | 406 KiB | 5 Q