Search code examples
phprequire

Why is my interface not found?


I'm learning PHP OOP and right now I built a basic calculator.

Here is my code at index.php:

require_once 'Calculator.class.php';
require_once 'Adder.class.php';
require_once 'Substract.class.php';
require_once 'Operator.interface.php';
require_once 'Multiplier.class.php';
require_once 'Devider.class.php';

$c = new Calculator;

$c->setOperation(new Adder);
$c->calculate(10,50); // 60

echo $c->getResult();

And this is the Calculator class file:

class Calculator
{
    protected $result;
    protected $operation;
    public function setOperation(OperatorInterface $operation)
    {
        $this->operation = $operation;
        // var_dump($operation);        
    }
    public function calculate()
    {
        foreach(func_get_args() as $number)
        {
            $this->result = $this->operation->run($number,$this->result);
        }
    }
    public function getResult()
    {
        return $this->result;
    }
}

And this is the interface that is being called within this class file:

interface OperatorInterface
{
    public function run($number,$result);
}

And this is the class Adder which is called from the index.php:

class Adder implements OperatorInterface
{
    public function run($number,$result)
    {
        return $result + $number;
    }
}

As you can see it looks nice and okay... however I get this weird error:

Fatal error: Interface 'OperatorInterface' not found on line 2 Adder.php

So line 2 of Adder Class is this:

class Adder implements OperatorInterface

Which means I have not include the interface properly. But I did include that.

So why am I getting this error?

Where did I make my mistake?


Solution

  • You need to include the Operator.interface.php file before the Adder.class.php file, otherwise when the compiler gets to the Adder class, it hasn't yet encountered anything called OperatorInterface, so it doesn't recognise it and can't verify that it's valid to declare that the Adder class implements it. Since it's also referenced in the Calculator class, you should include it before that as well.

    require_once 'Operator.interface.php';
    require_once 'Calculator.class.php';
    require_once 'Adder.class.php';
    require_once 'Substract.class.php';
    require_once 'Multiplier.class.php';
    require_once 'Devider.class.php';
    

    It should be that simple - for future reference you should always order your includes so that dependencies between them can be satisfied, because they get processed in the order you supply them.