On Tue, Jan 18, 2022 at 3:55 PM Jordan LeDoux <jordan.led...@gmail.com> wrote:
> 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; > } > } > This can still be handled with abstract methods trait ArithmeticTrait { public function add(float $val): NumberInterface { $n = $this->getNumberInterface(); // Do math return $n; } public function addmul(float $val): NumberInterface { $n = $this->getNumberInterface(); $added = $this->add($val); if ($added->isPositive()) { // Do stuff } return $n; } abstract protected function getNumberInterface(): NumberInterface; } class Foo { use ArithmeticTrait; protected NumberInterface $n; protected function getNumberInterface() : NumberInterface { return $this->n; } } > > 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 > -- Chase Peeler chasepee...@gmail.com