NoDiscard¶
NoDiscard attribute ensures that the returned value of a method is collected in the calling context. That value must be processed there, and not ignored, as it is important for the rest of the processing.
NoDiscard is already used internally, with flock and DateTimeImmutable::setTime(), to ensure that the result is checked.
<?php
#[\NoDiscard("This returns NULL in case of error")]
function foo(): ?array {}
$result = foo();
if ($result === null) {
throw new Exception('an error occured!');
}
?>
See also PHP RFC: Marking return values as important (#[NoDiscard]) and #[NoDiscard] — Warn When Return Values Are Ignored.
Related : Attribute, Attribute Class, PHP Native Attributes, PHP Native Attribute, (void) Cast
Added in PHP 8.5+