سؤال

What are the best usages of functions that end with "return;" and what are the advantages of writing a function that ends this way?

Example:

function MyFunction() {
 // (do something)
 return;
}

Thank you

هل كانت مفيدة؟

المحلول

You shouldn't, I would always use return null; so that it is an explicit declaration of what is returned (even if it is null). I'm sure this is also in one of the PSR specs as well, but I don't know them well. To confirm that return; === return null;:

function test() {
    return;
}

var_dump(test());
// NULL

As to when you would want to return null;..any function that returns something, should always return something. So maybe if you have a function that gathers and returns a value from a DB, and an error occurs:

public function retrieveData()
{
    $data = DB::retrieve();

    if(!$data) {
        return null;
    }

    return $data;
}

However, a lot of functions that may have errors just return true/false on success or failure so you won't necessarily use this often.

My main point to drive home: if you don't want/need to return anything, don't return anything.

نصائح أخرى

A return; says only "thats the end". Mostly useful in following examples:

 function test($string) {
      if(empty($string)) {
           return; // If the variable is empty, then stop to work!
      }

      echo $string;
 }

A simple example is that you can write a PHP function that spits out formatted HTML:

function printHeader($value)
{
  echo "<h1>$value</h1>";
  return;
}

However, since you are not returning anything, the return statement is unnecessary and can be left out.

If you are talking about a empty return;, I can think of one example, if you have code that should be executed under a condition, and more code that should be executed if that condition is not met.

function MyFunction() {
 if(a < 1) {
 // (do something)
 return;
 }
 // If a >= 0 it executes the code above and the code below
 // Do something else
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top