1

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.

2 Answers 2

1

In PHP 8.5, the new #[NoDiscard] attributes does exactly that: ensure the returned value is actually used. https://wiki.php.net/rfc/marking_return_value_as_important

Sign up to request clarification or add additional context in comments.

1 Comment

Looks exciting and is what I'm looking for. Can't wait for it to be released. When it's released, I'll be happy to accept this answer.
0

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.

3 Comments

Same applies to Rust. Example program fn main() { "test"; } runs without issues, yet the Rust compiler knows that you haven't used the return value at call-site (if the function or type is annotated with #[must_use]). Expressions turn into statements by using a semicolon which applies to PHP as well. The idea would be that the IDE could use this information to highlight that a return value has not been used at call site.
I now see you've tagged phpdoc. You're looking for something IDE specific rather than part of the language. Sorry I missed that on first reading.
It does not have to be IDE specific, but should be something that works out of the box – or using a library. Specifically, the question can be interpreted as "Can I do this using PHP only, so my IDE will detect it just like everything else?" and not "How do I get my IDE to do this?"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.