Since PHP 8.5, we can use the #[NoDiscard] attribute, which can be applied to a functions or class methods. When an attribute is used, PHP checks if the function or class method return value is utilized and issues a warning if it is ignored. This helps make functions safer by ensuring that important return values are not accidentally forgotten.
We can use the (void) to inform that ignoring returned value is intentional. While it does not affect the script execution, it can suppress warnings from #[NoDiscard] attribute and may also prevent diagnostics emitted by IDEs or static analysis tools.
<?php
#[NoDiscard]
function trimTrailingDot(string $input): string
{
return rtrim($input, '.');
}
$input = 'Testing...';
// Warning: The return value of function trimTrailingDot() should either be used
// or intentionally ignored by casting it as (void) in ...\main.php on line 13
trimTrailingDot($input);
echo trimTrailingDot($input); // OK
(void) trimTrailingDot($input); // OK
In the example, a developer might mistakenly think the function modifies the string in place and does not return a value. By adding #[NoDiscard] attribute, such misunderstandings can be prevented. PHP will emit a warning if the return value is ignored, ensuring that important results are either used or explicitly marked as intentionally discarded with (void).
Leave a Comment
Cancel reply