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.
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:
You might misuse the
add
method like this:Adding the
#[MustUseResult]
attribute to theMoney::add()
method means the result from the method call must be used.This would be reported as an error:
And this would be OK: