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"; }
Output for 7.1.25 - 7.1.30, 7.2.0 - 7.2.33, 7.3.0 - 7.3.31, 7.4.0 - 7.4.25, 8.0.0 - 8.0.12, 8.1rc1 - rc3
Pump = __33__ Pump = **AAA-50** Pump = **BBB-01** Pump = Fatal error: Uncaught InvalidArgumentException: FAIL in /in/C6h1o:18 Stack trace: #0 /in/C6h1o(50): AssemblyFactory->makeAssembly(Array) #1 {main} thrown in /in/C6h1o on line 18
Process exited with code 255.

preferences:
41.4 ms | 461 KiB | 5 Q