M
M
magary42015-11-22 21:41:02
symfony
magary4, 2015-11-22 21:41:02

What does it mean to pass an interface as a parameter?

It's not the first time I've seen code like

public function save(ModelInterface $model)
    {
        $modelName = $this->getModelName();
        $modelEvent = new ModelEvent($model);
        . . .

https://github.com/orocommerce/orocommerce/blob/ma...
is it done this way?
As far as I know, if I write some kind of smart class that is used in some system, then I define an interface and if someone wants to use their own instead of it, he simply implements it.
but in this code i suspect another idea

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Ernest Faizullin, 2015-11-22
@magary4

something like this ... if the interface is in the parameter, then we can pass any instance of the class that implements the specified interface there.

interface Berry {
    public function getSugar() {};
}
 
class Strawberries implements Berry {
    public function getSugar() {
        return 20;
    }
}
 
class Watermelon implements Berry {
    public function getSugar() {
        return 50;
    }
}
 
class Omnomnom() {
 
    public function printBerrySugar(Berry $berry) {
        return print($berry->getSugar());
    }
    
    public function test() {
        $this->printBerrySugar(new Strawberries ());
        $this->printBerrySugar(new Watermelon ());
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question