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?
Magic methods in PHP are special methods that are aimed to perform certain tasks. These methods are named with double underscore (__) as prefix. All these function names are reserved and can't be used for any purpose other than associated magical functionality. Magical method in a class must be declared public.
A PHP interface defines a contract which a class must fulfill. If a PHP class is a blueprint for objects, an interface is a blueprint for classes. Any class implementing a given interface can be expected to have the same behavior in terms of what can be called, how it can be called, and what will be returned.
"Method" is basically just the name for a function within a class (or class function). Therefore __METHOD__ consists of the class name and the function name called ( dog::name ), while __FUNCTION__ only gives you the name of the function without any reference to the class it might be in.
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. ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With