Re: RFC: Trait expects interface
| From: | Chase Peeler | Date: | Wed, 19 Jan 2022 15:07:20 +0000 |
| Subject: | Re: RFC: Trait expects interface | ||
| References: | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-116897@lists.php.net to get a copy of this message | ||
On Tue, Jan 18, 2022 at 3:55 PM Jordan LeDoux <jordan.ledoux@gmail.com>
wrote:
> On Tue, Jan 18, 2022 at 11:13 AM Rowan Tommins <rowan.collins@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
chasepeeler@gmail.com