Method %s::%s cannot be #[\NoDiscard]¶
Description¶
The #[\NoDiscard] attribute marks a function, method or closure so that the engine emits a warning whenever a caller ignores its return value. Certain magic methods, such as __construct, __destruct, __clone and __wakeup, are always invoked for their side effect and never return a usable value to the caller (new returns the object itself, not the constructor’s return value), so attaching #[\NoDiscard] to them is meaningless and rejected at compile time.
Example¶
<?php
class X {
#[\NoDiscard]
public function __construct() {}
}
new X();
?>
Literal Examples¶
Method X::__construct cannot be #[NoDiscard]
Solutions¶
Remove the
#[\NoDiscard]attribute from the magic method.If a discardable-value warning is needed, move the logic to a regular, non-magic method and mark that one instead.
Changed Behavior¶
This error may appear following an evolution in behavior, in previous versions. See ` <https://php-changed-behaviors.readthedocs.io/en/latest/behavior/.html>`_.