We can make a "Automatic dependenci injector" in classes when her constructors depends other classes (with type hint).
<?php
class Dependence1 {
function foo() {
echo "foo";
}
}
class Dependence2 {
function foo2() {
echo "foo2";
}
}
final class myClass
{
private $dep1;
private $dep2;
public function __construct(
Dependence1 $dependence1,
Dependence2 $dependence2
)
{
$this->dep1 = $dependence1;
$this->dep2 = $dependence2;
}
}
$constructor = new ReflectionMethod(myClass::class, '__construct');
$parameters = $constructor->getParameters();
$dependences = [];
foreach ($parameters as $parameter) {
$dependenceClass = (string) $parameter->getType();
$dependences[] = new $dependenceClass();
}
$instance = new myClass(...$dependences);
var_dump($instance);
?>
Results in:
object(myClass)#6 (2) {
["dep1":"myClass":private]=>
object(Dependence1)#4 (0) {
}
["dep2":"myClass":private]=>
object(Dependence2)#5 (0) {
}
}