3v4l.org

run code in 300+ PHP versions simultaneously
<?php class Instantiator { public $dependencies = []; public function instantiate($type) { return $this->instantiateInternal($type, []); } private function instantiateInternal($type, array $stack) { if (in_array($type, $stack)) { throw new Exception(vsprintf('Cycle detected for `%s` as %s', [ $type, print_r($stack, true), ])); } $stack[] = $type; $graph = []; if (isset($this->dependencies[$type])) { foreach ($this->dependencies[$type] as $dependentType) { $graph[$dependentType] = $this->instantiateInternal($dependentType, $stack); } } return $graph; } } $i1 = new Instantiator(); $i1->dependencies = [ 'A' => ['B', 'C'], 'B' => ['D'], 'C' => ['D'], 'D' => ['E'], ]; var_dump($i1->instantiate('A')); $i2 = new Instantiator(); $i2->dependencies = [ 'A' => ['B', 'C'], 'B' => ['D'], 'C' => ['D'], 'D' => ['A'], ]; var_dump($i2->instantiate('A'));

preferences:
48.05 ms | 402 KiB | 5 Q