【问题标题】:Laravel Helpers InterfaceLaravel 助手接口
【发布时间】:2016-02-07 11:57:43
【问题描述】:

简单的例子,我有以下帮助接口用于计算:

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's here。我希望能够做类似的事情:

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

【问题讨论】:

    标签: php laravel interface


    【解决方案1】:

    试试这个代码:

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

    【讨论】:

    • 是的,就是这样,虽然我相信我的界面对于我目前使用它的用途完全没用,但我仍在学习它们,谢谢你的回答:)
    猜你喜欢
    • 2011-02-10
    • 2020-11-19
    • 2019-01-31
    • 1970-01-01
    • 2020-10-12
    • 2018-11-21
    • 2013-09-02
    • 2020-02-10
    • 2018-04-05
    相关资源
    最近更新 更多