Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPStorm missing return statement

Tags:

php

phpstorm

This function

public function confirmation() {
  if (is_array($this->modules)) {
    if (isset($GLOBALS[$this->selected_module]) && 
        is_object($GLOBALS[$this->selected_module]) && 
        ($GLOBALS[$this->selected_module]->enabled)) {
      return $GLOBALS[$this->selected_module]->confirmation();
    }
  }
}

gives the notice

Missing return statement

Is there any solution to get the return outside of the brackets?

like image 768
Ronny Linsener Avatar asked Dec 07 '22 04:12

Ronny Linsener


2 Answers

What you have here is a single return inside a conditional. If the conditional is not satisfied then execution will reach the end of the function without hitting a return statement, which is equivalent to return null.

Therefore, one thing you can do is make the return null explicit:

if (...) {
    return $GLOBALS[$this->selected_module]->confirmation();
}
else {
    // Can also do this without an "else", it's a matter of style
    return null;
}

You could also move the conditional into the return value expression by using the ternary operator:

return is_array($this->modules) &&
       isset($GLOBALS[$this->selected_module]) && 
       is_object($GLOBALS[$this->selected_module]) && 
       $GLOBALS[$this->selected_module]->enabled)
       ? $GLOBALS[$this->selected_module]->confirmation()
       : null

However, this is arguably too much for a ternary operator to gracefully handle, so readability is perhaps an issue here.

like image 128
Jon Avatar answered Dec 08 '22 16:12

Jon


You are allowed to have multiple return statements in a single function.

Decide how your code should behave if things aren't set properly and put a default return statement at the end of the function. Or raise an exception if it is a full blown error condition that should never happen.

like image 45
Rob Baillie Avatar answered Dec 08 '22 16:12

Rob Baillie