17

I want to use interfaces, but some of my implementations rely on magic methods such as __invoke and __call. I have to remove signatures of methods that may be invoked magically (in any implementation) from the interface. Which leads to the anti pattern Empty Interface (Yeah, I just made that up).

How do you combine interfaces and magic methods in PHP?

Emanuel Landeholm
  • 1,396
  • 1
  • 15
  • 21
  • Maybe I misunderstand you. I tried to define a class Example that extends a ABase and implements IA. The interface method is declared abstract in Base and Example only has a __call() method. PHP says: PHP Fatal error: Class ABase contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (ABase::do_something) – Emanuel Landeholm Feb 11 '11 at 07:21
  • Well, the fundamentals: parent (Base) has an abstract method. Therefore, any child MUST implement the method. The same is with interfaces. So if Base implements IA, and Base declares its implementation of method as abstract, you are forced to implement the method in any child. The error says it all ^^ – usoban Feb 11 '11 at 07:51
  • Precisely, so abstract methods don't help. – Emanuel Landeholm Feb 11 '11 at 08:33

1 Answers1

16

Have all of the interface methods in your implementations dispatch to __call(). It involves a lot of crummy cut-and-paste work, but it works.

interface Adder {
    public function add($x, $y);
}

class Calculator implements Adder {
    public function add($x, $y) {
        return $this->__call(__FUNCTION__, func_get_args());
    }

    public function __call($method, $args) {
        ...
    }
}

At least the body of each method can be identical. ;)

David Harkness
  • 35,992
  • 10
  • 112
  • 134