一个简单的例子,我有以下计算辅助接口:
interface Calculation
{
public function calculate();
}
以下是几个实现了这个接口的类:
class One implements Calculation
{
public function calculate()
{
return some calculation;
}
}
class Two implements Calculation
{
public function calculate()
{
return some different calculation;
}
}
// and so on..
现在,我展示了下面的代码,但我想要能够摆脱这里的if语句。我希望能够做到像这样:
foreach($units as $unit)
{
$total = (new \App\Helpers\{$unit})->calculate();
}
我该如何处理这个问题?
foreach($units as $unit)
{
if($unit === 'One')
{
$total = (new \App\Helpers\One)->calculate();
}
if($unit === 'Two')
{
$total = (new \App\Helpers\Two)->calculate();
}
if($unit === 'Three')
{
$total = (new \App\Helpers\Three)->calculate();
}
if($unit === 'Four')
{
$total = (new \App\Helpers\Four)->calculate();
}
// and so on..
}