php version guide

PHP 8.5 `#[\NoDiscard]` Attribute

#[\NoDiscard] marks a function or method whose returned value should normally be consumed. PHP 8.5 warns when a caller silently ignores it, while (void) records an intentional discard.

Changes Worth Recognising

  • Use the attribute where ignoring a returned replacement, result, or error indicator is likely to be a bug.
  • Assign, return, or otherwise consume the value during normal use.
  • Cast to (void) when ignoring the value is deliberate.
  • Do not annotate every return value; warnings lose value when the signal is noisy.

Consume an Important Return Value

PHP example
<?php

#[\NoDiscard]
function normaliseEmail(string $email): string
{
    return strtolower(trim($email));
}

$email = normaliseEmail(' DEV@EXAMPLE.COM ');
echo $email . PHP_EOL;

// Prints:
// dev@example.com

Upgrade Review

  • Annotate APIs where dropped values create a plausible defect.
  • Fix accidental ignores rather than suppressing warnings reflexively.
  • Use (void) to communicate intentional discard during review.

The attribute helps value-returning APIs communicate correct use directly to callers.

Practice

Protect a Normalisation Result

Mark a string normalisation function as #[\NoDiscard]. Call it correctly, then intentionally ignore one call with (void) and explain why suppression should be rare.

Show solution

Consume the normal result in an assignment. Use (void)normalise($value); only when the call is intentionally made for another observable reason.