3

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

1 Answer 1

4

Try this code:

   foreach($units as $unit)
    {
     $class="\\App\\Helpers\\".$unit;
     $total=(new $class)->calculate();
    }
Sign up to request clarification or add additional context in comments.

1 Comment

Yeah that's it, although I believe my interface is totally useless for what I am using it for at this moment, I still am learning about them so, thanks for this answer :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.