Marking return values as important (#[\NoDiscard]) in PHP 8.5

Marcos Marcolin • March 5, 2025 • 1 min read

php php85 phprfc opensource

🐘💡 RFC: #[\NoDiscard] attribute in PHP 8.5?!

A new RFC currently under vote for PHP 8.5 proposes adding the #[\NoDiscard] attribute, which warns when the return value of a function or method isn't used.

⚠️ The problem?

Ignoring return values can lead to silent failures that are hard to detect. This RFC aims to make that behavior more explicit and reduce bugs, ensuring important return values are always checked.

⚙️ How does it work?

If a function is marked with #[\NoDiscard], PHP will emit a warning whenever its return value is ignored. If the developer wants to intentionally discard the return value, a (void) cast can be used.

The RFC is still under vote, but it has good chances of being approved.

So, would you like this feature?

Personally, yes, since its use is optional. Making it mandatory would be crazy, and I believe that will never happen.

Practical example

<?php

#[\NoDiscard("Check the return value to ensure correct processing.")]
function processItems(array $items): array 
{
    $results = [];

    foreach ($items as $item) {
        $results[] = random_int(0, 1);
    }

    return $results;
}

$items = ['foo', 'bar', 'baz'];

// ⚠️ Warning: The return value of function processItems() is expected to be consumed, Check the return value to ensure correct processing in %s on line %d
processItems($items);

// ✅ No warning, since the return value was used
$results = processItems($items);

// ✅ No warning, since the return value was intentionally discarded
(void) processItems($items);

You can read more about the proposal in the official post: click here.

What do you think of this new feature? Share your thoughts in the comments!

Share: