#[\NoDiscard] and the (void) cast

suggest change

Some functions are useless if you ignore what they return. DateTimeImmutable::modify() returns a new object and leaves the original alone, so $date->modify('+1 day'); on its own line does nothing. The same goes for a validator that returns a list of errors, a tryLock() that returns false when the lock is taken, or a wither on an immutable object. PHP runs such a call without complaint and the bug shows up much later.

PHP 8.5 added two features for this:

PHP 8.5 also added #[\Override] on properties and the #[\DelayedTargetValidation] attribute, which are covered at the end.

All examples need PHP 8.5. Related topics: Attributes, Immutability, Overriding and Typed class constants and constant expressions, which covers #[\Deprecated] and attributes on constants.

Marking a function with #[\NoDiscard]

Put the attribute on a function or method. Any call whose result isn't used gets an E_WARNING:

<?php
#[\NoDiscard]
function withoutExpired(array $sessions, int $now): array
{
    return array_filter($sessions, fn($s) => $s['expires'] > $now);
}

$sessions = [
    ['id' => 'a', 'expires' => 100],
    ['id' => 'b', 'expires' => 300],
];

withoutExpired($sessions, 200);    // bug: the result is thrown away
echo count($sessions), "\n";

$sessions = withoutExpired($sessions, 200);
echo count($sessions), "\n";

Output:

Warning: The return value of function withoutExpired() should either be used or intentionally ignored by casting it as (void) in ... on line 13
2
1

The call on line 13 still runs and returns its result. The warning only tells you that the result was dropped. The second call assigns the result, so it gets no warning.

Adding a message

NoDiscard takes an optional $message string that explains why the result matters. PHP appends it to the warning after a comma, so a message that starts with "as" reads best. The built-in attributes on DateTimeImmutable are worded the same way.

<?php
final class Mutex
{
    #[\NoDiscard("as the lock is not held when false is returned")]
    public static function tryAcquire(string $name): bool
    {
        return $name !== 'busy';
    }
}

Mutex::tryAcquire('busy');

if (!Mutex::tryAcquire('reports')) {
    exit("another worker is running\n");
}
echo "lock acquired\n";

Output:

Warning: The return value of method Mutex::tryAcquire() should either be used or intentionally ignored by casting it as (void), as the lock is not held when false is returned in ... on line 11
lock acquired

For methods the warning says "method Class::name()" and for functions "function name()". Namespaced functions show their full name, such as App\b().

Ignoring a result on purpose with (void)

Sometimes ignoring the result is the right thing to do. For those calls PHP 8.5 adds the (void) cast:

<?php
#[\NoDiscard]
function writeCache(string $key, string $value): bool
{
    echo "writing $key\n";
    return true;
}

// The cache is best-effort: a failed write is fine here.
(void) writeCache('home', '<html>...</html>');

// (void) works on any expression, with or without the attribute.
(void) strlen('abc');
echo "done\n";

Output:

writing home
done

The call still runs. (void) only says "I know there is a result and I don't want it", which is also useful for code review: a reader can tell that ignoring the value was a decision.

Unlike (int) or (string), (void) doesn't produce a value. It can only start an expression statement, so you can't use it inside a larger expression:

<?php
$x = (void) strlen('abc');

Output:

Parse error: syntax error, unexpected token "(void)" in ... on line 2

Assigning the result to a throwaway variable ($_ = writeCache(...)) also avoids the warning, but (void) states the intent more clearly and leaves no unused variable for static analyzers to report.

What counts as using the result

The check happens at the call site. Any call whose return value goes somewhere is fine. Only a call used as a statement on its own triggers the warning:

<?php
#[\NoDiscard]
function total(array $xs): int { return array_sum($xs); }

$t = total([1, 2]);                 // assigned
echo total([1, 2]), "\n";           // passed to echo
printf("%d\n", total([3]));         // passed as an argument
if (total([]) === 0) {              // used in a condition
    echo "empty\n";
}
$f = 'total';
$f([1]);                            // dynamic call: still checked
$g = total(...);
$g([1]);                            // first-class callable: still checked
call_user_func('total', [1]);       // also checked
@total([1]);                        // @ silences the warning like any other

Output:

3
3
empty

Warning: The return value of function total() should either be used or intentionally ignored by casting it as (void) in ... on line 12

Warning: The return value of function total() should either be used or intentionally ignored by casting it as (void) in ... on line 14

Warning: The return value of function total() should either be used or intentionally ignored by casting it as (void) in ... on line 15

The engine checks dynamic calls, first-class callables and call_user_func() too, not just direct calls in the source. Don't use @ to silence it: (void) does the same job and doesn't hide other errors.

The warning is raised before the call

The warning is emitted before the function body runs. Usually that doesn't matter, but if your error handler turns warnings into exceptions (many frameworks do this), the function never runs:

<?php
set_error_handler(function (int $no, string $msg, string $file, int $line): bool {
    throw new ErrorException($msg, 0, $no, $file, $line);
});

#[\NoDiscard]
function charge(int $cents): bool
{
    echo "charging $cents cents\n";
    return true;
}

try {
    charge(500);
} catch (ErrorException $e) {
    echo "caught: ", $e->getMessage(), "\n";
}

$ok = charge(500);
var_dump($ok);

Output:

caught: The return value of function charge() should either be used or intentionally ignored by casting it as (void)
charging 500 cents
bool(true)

The first call threw before "charging" was printed. Keep this in mind when you add #[\NoDiscard] to an existing function in a library: under a strict error handler, callers that ignored the result get an exception and the function's side effects never happen. Mention it in your changelog.

Built-in methods marked #[\NoDiscard]

PHP 8.5 puts the attribute on the DateTimeImmutable methods that return a modified copy. Calling them as statements is a common bug, because the same code works with the mutable DateTime:

<?php
$start = new DateTimeImmutable('2026-03-01');

$start->modify('+1 month');      // does nothing: a new object is returned
echo $start->format('Y-m-d'), "\n";

$next = $start->modify('+1 month');
echo $next->format('Y-m-d'), "\n";

$mutable = new DateTime('2026-03-01');
$mutable->modify('+1 month');    // DateTime changes itself: no warning
echo $mutable->format('Y-m-d'), "\n";

Output:

Warning: The return value of method DateTimeImmutable::modify() should either be used or intentionally ignored by casting it as (void), as DateTimeImmutable::modify() does not modify the object itself in ... on line 4
2026-03-01
2026-04-01
2026-04-01

The attribute is visible through reflection, so you can list the marked methods:

<?php
$methods = [];
foreach ((new ReflectionClass(DateTimeImmutable::class))->getMethods() as $m) {
    if ($m->getAttributes(NoDiscard::class)) {
        $methods[] = $m->getName();
    }
}
echo implode(', ', $methods), "\n";

Output:

modify, add, sub, setTimezone, setTime, setDate, setISODate, setTimestamp, setMicrosecond

In PHP 8.5.11, with all bundled extensions loaded, these are the only internal functions or methods that carry the attribute.

Rules enforced at compile time

A function marked #[\NoDiscard] has to return something. A void or never return type is a compile error:

<?php
#[\NoDiscard]
function log_line(string $msg): void
{
    echo $msg, "\n";
}

Output:

Fatal error: A void function does not return a value, but #[\NoDiscard] requires a return value in ... on line 3
Stack trace:
#0 {main}

With never the message reads "A never returning function does not return a value...". (The Stack trace lines come from PHP 8.5, which adds backtraces to fatal errors.)

A function without a return type is allowed, even if it never returns anything. A ?int function that returns null is also allowed. The check is about the call site, not the value.

Constructors can't be marked, because new always produces a value:

<?php
class Connection
{
    #[\NoDiscard]
    public function __construct() {}
}

Output:

Fatal error: Method Connection::__construct cannot be #[\NoDiscard] in ... on line 5
Stack trace:
#0 {main}

The attribute only targets functions and methods (closures and arrow functions included). Putting it on a class or property gives Attribute "NoDiscard" cannot target class (allowed targets: function, method).

In namespaced code write the leading backslash (or use NoDiscard;). Otherwise the name resolves to a class in the current namespace, which doesn't exist, and PHP ignores the attribute without any error:

<?php
namespace App;

#[NoDiscard]            // resolves to App\NoDiscard: silently ignored
function a(): int { return 1; }

#[\NoDiscard]
function b(): int { return 2; }

a();
b();

Output:

Warning: The return value of function App\b() should either be used or intentionally ignored by casting it as (void) in ... on line 11

The attribute is not inherited

#[\NoDiscard] applies to the function that actually runs. An overriding method or an interface implementation doesn't get it from the parent:

<?php
interface Repository
{
    #[\NoDiscard]
    public function insert(array $row): int;
}

class SqlRepository implements Repository
{
    public function insert(array $row): int { return 42; }
}

class Base
{
    #[\NoDiscard]
    public function id(): int { return 1; }
}

class Child extends Base
{
    public function id(): int { return 2; }
}

(new SqlRepository)->insert(['name' => 'x']);   // no warning
(new Child)->id();                               // no warning
(new Base)->id();                                // warning

Output:

Warning: The return value of method Base::id() should either be used or intentionally ignored by casting it as (void) in ... on line 26

On an interface the attribute is documentation for implementers. Repeat it on every implementation that should be checked. The same applies to calls through a variable typed as the interface: what matters is the class of the object at runtime.

When to use #[\NoDiscard]

The attribute is for functions where ignoring the result is almost always a bug. Typical cases:

Here's an immutable Money class. Its withers use PHP 8.5's clone with property overrides (see Immutability):

<?php
final readonly class Money
{
    public function __construct(
        public int $cents,
        public string $currency,
    ) {}

    #[\NoDiscard("as Money is immutable")]
    public function add(Money $other): static
    {
        if ($other->currency !== $this->currency) {
            throw new InvalidArgumentException('currency mismatch');
        }
        return clone($this, ['cents' => $this->cents + $other->cents]);
    }

    #[\NoDiscard("as Money is immutable")]
    public function withCurrency(string $currency): static
    {
        return clone($this, ['currency' => $currency]);
    }

    public function __toString(): string
    {
        return sprintf('%d.%02d %s', intdiv($this->cents, 100), $this->cents % 100, $this->currency);
    }
}

$price = new Money(1999, 'EUR');
$price->add(new Money(500, 'EUR'));       // looks like it updates $price
echo $price, "\n";

$total = $price->add(new Money(500, 'EUR'));
echo $total, "\n";
echo $total->withCurrency('USD'), "\n";

Output:

Warning: The return value of method Money::add() should either be used or intentionally ignored by casting it as (void), as Money is immutable in ... on line 31
19.99 EUR
24.99 EUR
24.99 USD

And a validator that returns its errors as a value instead of throwing:

<?php
final class ValidationResult
{
    /** @param list<string> $errors */
    public function __construct(public readonly array $errors = []) {}

    public function isValid(): bool
    {
        return $this->errors === [];
    }
}

final class SignupValidator
{
    #[\NoDiscard("as invalid input must not be saved")]
    public function validate(array $input): ValidationResult
    {
        $errors = [];
        if (!filter_var($input['email'] ?? '', FILTER_VALIDATE_EMAIL)) {
            $errors[] = 'email is invalid';
        }
        if (strlen($input['password'] ?? '') < 12) {
            $errors[] = 'password is too short';
        }
        return new ValidationResult($errors);
    }
}

$validator = new SignupValidator();
$input = ['email' => 'bob@', 'password' => 'hunter2'];

$validator->validate($input);   // validation that is never checked
echo "saving user...\n";

$result = $validator->validate($input);
if (!$result->isValid()) {
    echo implode("\n", $result->errors), "\n";
}

Output:

Warning: The return value of method SignupValidator::validate() should either be used or intentionally ignored by casting it as (void), as invalid input must not be saved in ... on line 32
saving user...
email is invalid
password is too short

Don't use it where the return value is optional information:

Static analyzers such as PHPStan and Psalm already report unused results of pure functions. #[\NoDiscard] works at runtime too, needs no extra tools, and the author of the function decides what is checked.

Compatibility with older PHP versions

Attributes have existed since PHP 8.0. Older versions don't check attributes whose class doesn't exist, so a library can add #[\NoDiscard] while still supporting PHP 8.0 to 8.4. There it does nothing.

The (void) cast is new syntax, though. A file that uses it is a syntax error on PHP 8.4 and older. If your code has to run on older versions, assign to a throwaway variable instead:

$_ = writeCache('home', $html); // works on any PHP version

#[\Override] on properties (PHP 8.5)

PHP 8.3 added #[\Override] for methods (see Overriding). PHP 8.5 also allows it on properties. The property must redeclare a property of a parent class, or implement a property declared in an interface (PHP 8.4 added interface properties with hooks):

<?php
interface HasLabel
{
    public string $label { get; }
}

abstract class Widget
{
    public string $color = 'black';
    public function __construct(public int $width = 100) {}
}

class Button extends Widget implements HasLabel
{
    #[\Override]
    public string $color = 'blue';

    #[\Override]
    public string $label {
        get => 'OK';
    }

    public function __construct(#[\Override] public int $width = 80)
    {
    }
}

$b = new Button();
echo "$b->label $b->color $b->width\n";

Output:

OK blue 80

It also works on promoted constructor properties, as $width shows. If the parent property is renamed or misspelled, the class fails to compile:

<?php
class Button
{
    #[\Override]
    public string $colour = 'blue';
}

Output:

Fatal error: Button::$colour has #[\Override] attribute, but no matching parent property exists in ... on line 2
Stack trace:
#0 {main}

#[\DelayedTargetValidation] (PHP 8.5)

Every attribute declares which targets it allows: NoDiscard allows functions and methods, Override methods and (since 8.5) properties. Internal attributes are checked at compile time, so an internal attribute on the wrong kind of declaration is a fatal error:

<?php
#[\NoDiscard]           // NoDiscard cannot target a class
class Report {}

echo "compiled\n";

Output:

Fatal error: Attribute "NoDiscard" cannot target class (allowed targets: function, method) in ... on line 3
Stack trace:
#0 {main}

This is a problem when a newer PHP version allows an attribute on more targets, as 8.5 did for #[\Override] on properties and #[\Deprecated] on global constants. Code written for the newer version breaks the older one at compile time. Adding #[\DelayedTargetValidation] to the declaration moves the target check for internal attributes from compile time to reflection, the same way userland attributes behave:

<?php
#[\DelayedTargetValidation]
#[\NoDiscard]           // NoDiscard cannot target a class
class Report {}

echo "compiled\n";

$attr = (new ReflectionClass(Report::class))->getAttributes(NoDiscard::class)[0];
try {
    $attr->newInstance();
} catch (Error $e) {
    echo $e->getMessage(), "\n";
}

Output:

compiled
Attribute "NoDiscard" cannot target class (allowed targets: function, method)

On an unsupported target the attribute has no effect. The error only shows up if something calls newInstance().

#[\DelayedTargetValidation] only delays the target check. Other checks stay at compile time. #[\Override] on a property without a parent property is still a fatal error, and so is #[\NoDiscard] on a void function. The attribute is itself new in 8.5, so it helps with attributes that get new targets in PHP 8.6 and later. It can't make #[\Override] on a property compile on PHP 8.4.

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents