php - Laravel 助手接口(interface)

标签 php laravel interface

简单的例子,我有以下用于计算的辅助接口(interface):

interface Calculation
{
    public function calculate();
}

还有几个实现这个接口(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..

现在,在我看来,我有下面显示的代码,但我希望能够摆脱此处的 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..
}

最佳答案

试试这段代码:

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

关于php - Laravel 助手接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35253161/

相关文章:

php - 如何在 .htaccess 中为 CDN 添加利用浏览器缓存?

php - 用表格中的 Logo 替换团队名称

php - 如何在 Laravel 5 中使用 AJAX 发送数据?

Java 二进制兼容性问题 : sun. font.FontManager 类成为接口(interface)

php - 在 PHP 生成的 Javascript 中转义撇号

php - 如何使用PHP在分页中添加事件类

laravel - 如何在 Laravel 4 中获取 @if 语句(Blade)中的当前 URL?

css - Laravel 覆盖 Bootstrap 模板

php - 界面类型提示

methods - 难以理解一段 golang 代码