How PHP’s #[\NoDiscard] Attribute Prevents Silent Return‑Value Bugs
The article explains PHP 8.5’s #[\NoDiscard] attribute, showing how it forces developers to handle function return values, provides syntax and usage examples, demonstrates real‑world scenarios, and describes ways to suppress warnings when the return value is intentionally ignored.
What is #[\NoDiscard] attribute?
When a function or method is marked with #[\NoDiscard], PHP signals that its return value must be used; ignoring it triggers a warning (E_WARNING or E_USER_WARNING). Using the value in an assignment, expression, or type cast counts as "using" it.
Using #[\NoDiscard] attribute
Below is a simple function that returns a sum, followed by a call that forgets the return value, which would raise a warning if the function were annotated.
function calculateSum(int $a, int $b): int {
return $a + $b;
}
$result = calculateSum(5, 10);
// Forgetting the return value
calculateSum(5, 10);Attribute definition
#[Attribute(Attribute::TARGET_METHOD|Attribute::TARGET_FUNCTION)]
final class NoDiscard {
public readonly ?string $message;
public function __construct(?string $message = null) {}
}Using #[\NoDiscard] attribute
Annotate a function whose result is important; PHP will warn if the caller discards the return value.
#[\NoDiscard("as the operation result is important")]
function performOperation(): int {
// perform some work
return 1; // 1 = success, 0 = failure
}
// Call without using the return value → warning
performOperation();
// Call with assignment → no warning
$status = performOperation();Real‑world example
A bulk‑processing function returns an array of errors; ignoring the result triggers a warning because some items may fail.
#[\NoDiscard("as processing might fail for individual items")]
function bulk_process(array $items): array {
$results = [];
foreach ($items as $key => $item) {
if (\random_int(0, 9999) < 9999) {
echo "Processing {$item}", PHP_EOL;
$error = null;
} else {
$error = new \Exception("Failed to process {$item}.");
}
$results[$key] = $error;
}
return $results;
}
$items = ['foo', 'bar', 'baz'];
// Warning because return value is ignored
bulk_process($items);
// No warning because the result is stored
$results = bulk_process($items);Explicit conversion to void or another type
If you intentionally want to discard a return value without a warning, cast it to void (available in PHP 8.5) or another type.
// No warning – explicit void cast
(void) bulk_process($items);
// No warning – cast to bool (may be optimized away by OPcache)
(bool) bulk_process($items);Inspiration
The feature draws inspiration from similar attributes in C++ and Rust that help catch bugs caused by ignored return values.
Summary
#[\NoDiscard]is a safety attribute for PHP developers that forces attention to return values, especially when they indicate success or failure, thereby reducing hard‑to‑detect bugs in large codebases.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Open Source Tech Hub
Sharing cutting-edge internet technologies and practical AI resources.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
