功能實(shí)現(xiàn)
基于example1的Container實(shí)現(xiàn),添加對(duì)基本數(shù)據(jù)類(lèi)型以及mixed
變量的實(shí)現(xiàn)支持(賦默認(rèn)值)
代碼實(shí)現(xiàn) Container
public function create($abstract)
{
// temporary constraint
static $times = 0;
if (++$times > 100) {
$times = 0;
throw new class('exec too many times in create method.') extends Exception implements ContainerExceptionInterface{ };
}
$refClass = new ReflectionClass($abstract);
if ($refClass->getName() === Closure::class) {
return function (){};
} elseif ($refClass->hasMethod('__construct')) {
$_constructParams = array_map(function (ReflectionParameter $param) {
if ($param->getClass()) {
return $this->create($param->getClass()->getName());
} elseif ($param->isDefaultValueAvailable()) {
return $param->getDefaultValue();
} elseif ($param->getType()) {
return ([
'string' => '',
'int' => 0,
'array' => [],
'bool' => false,
'float' => 0.0,
'iterable' => [],
'callable' => function() {}
])[$param->getType()->getName()] ?? null;
} else {
return null;
}
}, $refClass->getMethod('__construct')->getParameters());
}
return $refClass->newInstance(... ($_constructParams ?? []));
}
- 以下代碼主要用于限制方法的最大執(zhí)行次數(shù),防止相互依賴(lài)造成的程序死循環(huán)晴股,本例忽略此段代碼
// temporary constraint
static $times = 0;
if (++$times > 100) {
$times = 0;
throw new class('exec too many times in create method.') extends Exception implements ContainerExceptionInterface{ };
}
實(shí)現(xiàn)思路
- 列出無(wú)法以類(lèi)解析或者無(wú)法通過(guò)new創(chuàng)建的類(lèi)(僅考慮PHP內(nèi)部的類(lèi))參數(shù)列表的數(shù)據(jù)類(lèi)型
string
int
array
bool
float
iterable
callable
Closure