3v4l.org

run code in 300+ PHP versions simultaneously
<?php class AssemblyFactory { public const PUMPMETHODS = [ 'modelNumber' => 'fromModelNumber', 'productId' => 'fromProductId' ]; public $pumpFactory; public function __construct () { $this->pumpFactory = new PumpFactory(); } public function makeAssembly(array $params) { $validMethods = array_intersect_key(self::PUMPMETHODS, $params); if (!$validMethods) { throw new \InvalidArgumentException("FAIL"); } else { foreach ($validMethods as $paramKey => $methodName) { return $this->pumpFactory->{$methodName}($params[$paramKey]); } } } } class PumpFactory { public function fromProductId($id) { return "__{$id}__"; } public function fromModelNumber($id) { return "**{$id}**"; } } $factory = new AssemblyFactory(); $tests = [ ['productId' => 33], ['modelNumber' => 'AAA-50'], ['productId' => 1, 'modelNumber' => 'BBB-01'], ['invalidKey' => 'nope'] ]; foreach ($tests as $testParams) { $factory = new AssemblyFactory; echo "Pump = " , $factory->makeAssembly($testParams), "\n"; }

preferences:
35.77 ms | 458 KiB | 5 Q