Is it possible to specify, either in plain PHP 8+ or PHPDoc that a function return value must be used, like the Rust equivalent?
Imagine a function:
public function doSomething(): ImportantObject {
return (new ImportantObject)->withImportantStuff();
}
I would like to annotate it something like this:
/**
* @mustUse
* @return ImportantObject
*/
public function doSomething(): ImportantObject {
return (new ImportantObject)->withImportantStuff();
}
Or:
#[must_use]
public function doSomething(): ImportantObject {
return (new ImportantObject)->withImportantStuff();
}
The use case for this would be so developers get a warning in their IDE that they have to use the value or, otherwise, their code would not be sound or be less robust.
The problem here is the defintion of "use". In PHP an expression is a statement and vice versa, so
"fred";is a valid complete statement. It just doesn't do anything.If something returns a value then that value is used. In your example
doSomething();as a statement does use the return value, it just doesn't do anything with it.