PHP 8.5 adds the #[\NoDiscard] attribute for functions and methods whose return values should normally be used. If a caller ignores the result, PHP emits a warning.
Mark a Function as NoDiscard
Example:
<?php
#[\NoDiscard]
function saveOrder(): bool
{
return true;
}
saveOrder();
Because the result is ignored, PHP 8.5 warns that the return value should either be used or intentionally discarded.
Use the Return Value
Example:
<?php
#[\NoDiscard]
function saveOrder(): bool
{
return true;
}
if (saveOrder()) {
echo 'Saved';
}
No warning is needed because the result affects program behavior.
Intentionally Ignore a Result
PHP 8.5 also supports the (void) cast for explicitly discarding a result.
After the earlier saveOrder() definition:
Example:
(void) saveOrder();
This tells readers and PHP itself that ignoring the value is deliberate.
Good Candidates
- Validation results that must be checked
- Operations where failure is reported through the return value
- Functions that return a new immutable object
- APIs where silently ignoring the result is likely to be a bug
Methods Can Use It Too
Example:
<?php
final class Price
{
public function __construct(public readonly int $cents) {}
#[\NoDiscard]
public function withCents(int $cents): self
{
return new self($cents);
}
}
$original = new Price(2500);
$updated = $original->withCents(2200);
echo $original->cents . PHP_EOL . $updated->cents;
Output:
2500
2200
Backward Compatibility
The attribute can be present in code supporting earlier PHP versions, but its warning is enforced only in PHP 8.5 and later. The (void) cast itself requires PHP 8.5; use an assignment such as $_ = saveOrder(); when older PHP versions must parse the code.
| Caller action | Result |
|---|---|
| Uses return value | No warning |
| Ignores return value | Warning |
| Casts to void | Intentional discard |
Use #[\NoDiscard] selectively. Adding it to functions whose return values are commonly optional creates noise rather than useful feedback.
Conclusion
#[\NoDiscard] helps API authors communicate that a return value matters. It is most useful when ignoring the result can hide an error or make code behave incorrectly.