Question

I have a function, where if a variable is not defined, exit; is called, therefor it should not produce anything on the page but a blank page. it produces an error message right before it is exited actually. so when its supposed to execute, because the variable is not defined, it should die, but what happens is the error message is executed, then the rest of the page loads under the error message, and does not exit. any ideas?

public function exit_error() {
    parent::error_array();
    $errors = $this->msg_array;
    return $errors;
    die(); // error should produce, then die here.
}
Was it helpful?

Solution

With this line:

return $errors;

the function exits and returns the result to the caller.
Anything that comes after the return statement is never executed!

You can think about return as letting the function say: "Here take this, I am finished here!".


Because of this it is possible to have multiple return statements in a function e.g :

function($i) {
   if($i > 0) {
       return 'foo';
   }
   $i = -$i;
   return 'bar';
}

The function is nonsense, the point is that if $i is larger then 0, the statement return 'foo' is reached, the function exists and never executes the following lines.

With this you can leave a function early without doing further computations that might not be necessary.

OTHER TIPS

You're returning from your function before your code reaches exit. This is what return does. Everything after the return statement is ignored, and the flow of execution returns to the point at which you called the function.

Read more about return and program flow here. it's a basic concept and understanding it is vital if you hope to write even the simplest programs.

By using return, you are basically exiting out of your function. Any subsequent statements are ignored, including die().

Oh, and save a unicorn and use exit() instead ;). (This is a joke, die() is equivalent to exit() in PHP)

the funciton is returning the variable $errors and then no more of the code within the function is executed.

    public function exit_error() {
        parent::error_array();
        $errors = $this->msg_array;
        return $errors;
        echo "hello";
        die();
    }

Hello will never be printed because the function has stopped executing.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top