Skip to content

Instantly share code, notes, and snippets.

@devmsh
Forked from akramabdulrahman/index.php
Last active June 19, 2017 12:01
Show Gist options
  • Save devmsh/c4d7085089da87593d133accedef4a16 to your computer and use it in GitHub Desktop.
Save devmsh/c4d7085089da87593d133accedef4a16 to your computer and use it in GitHub Desktop.
IoC implementation
<?php
class B
{
public $name = 'akram';
}
class A
{
private $b;
public function getB()
{
return $this->b;
}
function __construct(B $b)
{
$this->b = $b;
}
}
class Container
{
public static function make($className)
{
$reflection = new ReflectionClass($className);
$constructor = $reflection->getConstructor();
if ($constructor && count($constructor->getParameters())) {
$args = array_map(function ($param) {
return Container::make($param->getClass()->name);
}, $constructor->getParameters());
return $reflection->newInstanceArgs($args);
} else {
return new $className();
}
}
}
$b = Container::make(B::class); // no problem
$a = Container::make(A::class); // Too few arguments exception
var_dump($a->getB());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment