DaveLiddament / php-language-extensions

Attributes to define new PHP language features (that are enforced by static analysis)
MIT License
135 stars 5 forks source link

Add #[MustUseResult] #30

Closed DaveLiddament closed 3 months ago

DaveLiddament commented 3 months ago

Add #[MustUseResult] attribute that can be used on methods. This enforces the result from the method call must be used.

E.g. if you has a class like this:

class Money {

  public function __construct(public readonly int $pence) 
  {}

  public function add(int $pence): self 
  {
     return new self($pence + $this->pence);
  }
}

You might misuse the add method like this:

$cost = new Money(5);
$cost->add(6); // this has not modified $cost

Adding the #[MustUseResult] attribute to the Money::add() method means the result from the method call must be used.

This would be reported as an error:

$cost->add(6); 

And this would be OK:

$updatedCost = $cost->add(6);
DaveLiddament commented 3 months ago

Implemented by #31