Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use interfaces and magic methods in PHP

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?

like image 393
Emanuel Landeholm Avatar asked Feb 11 '11 06:02

Emanuel Landeholm


People also ask

What is the use of 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.

What is the use of interface in PHP?

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.

What is __ method __ in PHP?

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


1 Answers

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. ;)

like image 189
David Harkness Avatar answered Oct 18 '22 17:10

David Harkness