Laravel助手界面

时间:2016-02-07 11:57:44

标签: php laravel interface

简单的例子,我有以下帮助程序接口进行计算:

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..
}

1 个答案:

答案 0 :(得分:4)

试试这段代码:

   foreach($units as $unit)
    {
     $class="\\App\\Helpers\\".$unit;
     $total=(new $class)->calculate();
    }