Published
10: The NoDiscard Attribute to Prevent Unhandled Return Values
Sometimes a function performs an operation where ignoring its returned result leads to logic bugs or memory leaks—for instance, pure calculation functions or state modifications that return a new object. PHP 8.5 introduces the #[\NoDiscard] attribute. When applied to a function or method, PHP will emit a warning if the caller invokes the function without capturing or using its return value.
PHP 8.5 Example:
PHP
class Calculator
{
#[\NoDiscard("The result of add() must be used or assigned.")]
public function add(int $a, int $b): int
{
return $a + $b;
}
}
$calc = new Calculator();
$calc->add(5, 10); // Emits a warning because the returned value was discarded!The articles and images featured on this platform were generated with the assistance of AI tools.