On Tue, Jan 18, 2022 at 11:13 AM Rowan Tommins <rowan.coll...@gmail.com>
wrote:

>
> The difference with the "trait requires interface" proposal is that I
> don't understand what advantage it gives the author of the trait. What
> decisions can you make as a library developer because you've said "users
> of this trait must implement the matching interface" as opposed to "...
> can implement the matching interface"?
>
> It's possible there is some advantage I'm missing, but so far nobody
> seems to have presented it.
>
>
Well, the trait doesn't necessarily have to fulfill the entire interface,
first of all. As you mentioned, this can be worked around using abstracts
in the trait. However, what if you're dealing with return values within the
trait?

Suppose I have something like this:

trait ArithmeticTrait {
    public function add(float $val): NumberInterface {
        // Do math

        return $this;
    }

    public function addmul(float $val): NumberInterface {
        $added = $this->add($val);

        if ($added->isPositive()) {
            // Do stuff
        }

        return $this;
    }
}

In this situation, the return value of the trait requires that $this
implements the NumberInterface, however there is no way for the trait
itself to enforce this.

Jordan

Reply via email to