<?php
class locator {
public $instances;
public function setDef($name, $instance){
$this->instances[$name] = $instance;
}
public function get($name){
if(isset($this->instances[$name])){
$o = (new ReflectionClass($name))->getConstructor();
if($o === null || null === $o->getParameters()){
return new $this->instances[$name]();
} else {
$p = $o->getParameters();
$instancesArray = [];
foreach($p as $i){
$instancesArray[] = $this->get($i->getClass()->name);
}
$inst = new ReflectionClass($this->instances[$name]);
return $inst->newInstanceArgs($instancesArray);
}
}
}
}
class z {
public $z = "zzzzzz";
}
class base {
public $b = "base !!!";
}
class second {
public $z;
public $s = "second !!!";
public function __construct(z $a){
$this->z = $a;
}
}
class a {
public $base;
public $second;
public function __construct(base $b, second $s){
$this->base = $b;
$this->second = $s;
}
}
$loc = new locator();
$loc->setDef('z', z::class);
$loc->setDef('second', second::class);
$loc->setDef('base', base::class);
$loc->setDef('a', a::class);
$o = $loc->get('a');
echo $o->base->b;
echo "<br>";
echo $o->second->s;
echo "<br>";
echo $o->second->z->z;
?>
Deprecated: Method ReflectionParameter::getClass() is deprecated in /in/VgRC1 on line 16
Deprecated: Method ReflectionParameter::getClass() is deprecated in /in/VgRC1 on line 16
Deprecated: Method ReflectionParameter::getClass() is deprecated in /in/VgRC1 on line 16
base !!!<br>second !!!<br>zzzzzz
Output for 8.3.5
Warning: PHP Startup: Unable to load dynamic library 'sodium.so' (tried: /usr/lib/php/8.3.5/modules/sodium.so (libsodium.so.23: cannot open shared object file: No such file or directory), /usr/lib/php/8.3.5/modules/sodium.so.so (/usr/lib/php/8.3.5/modules/sodium.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0
Deprecated: Method ReflectionParameter::getClass() is deprecated in /in/VgRC1 on line 16
Deprecated: Method ReflectionParameter::getClass() is deprecated in /in/VgRC1 on line 16
Deprecated: Method ReflectionParameter::getClass() is deprecated in /in/VgRC1 on line 16
base !!!<br>second !!!<br>zzzzzz