Simple example, I have the following helpers interface for calculations:
interface Calculation
{
public function calculate();
}
And a few classes that implement this interface:
class One implements Calculation
{
public function calculate()
{
return some calculation;
}
}
class Two implements Calculation
{
public function calculate()
{
return some different calculation;
}
}
// and so on..
Now, in my view I have the code that I displayed below, but I want to be able to get rid of the if's here. I would like to be able to do something like:
foreach($units as $unit)
{
$total = (new \App\Helpers\{$unit})->calculate();
}
How would I go about this?
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..
}