3v4l.org

run code in 200+ php & hhvm versions
Bugs & Features
<?php // The smallest, ugliest autowiring container. function dep_set($n, $v) { $GLOBALS['deps'][$n] = $v; } function dep_get($n) { $v = &$GLOBALS['deps'][$n]; if (!$v) $v = $n; $r = $v instanceof Closure ? new ReflectionFunction($v) : (new ReflectionClass($n))->getConstructor(); $a = []; foreach ($r->getParameters() as $i => $p) { $pc = $p->getClass(); if (!$pc) throw new Exception('Cannot magically resolve a param $' . $p->name . ' without class typehint'); $pn = $pc->name; $a[] = dep_get(isset($GLOBALS['deps'][$n . '@' . $pn]) ? $n . '@' . $pn : $pn); } $v = $v instanceof Closure ? $v(...$a) : new $v(...$a); return $v; } // Usage: class A { function __construct($a, $b) { echo $a + $b; // 3 } function b() { echo 4; } } class B { function __construct(A $a) { $a->b(); } } class C { function __construct(B $a) { } } dep_set(A::class, function () { return new A(1, 2); }); $c = dep_get(C::class); // Instantiates A, B, C and prints "34"
Output for 5.6.0 - 5.6.30, hhvm-3.15.4, 7.0.0 - 7.2.6
34