Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When a PHP function is called and something is RETURNED, does it stop running the code below it?

Tags:

php

I am just studying other user's PHP code right now to understand and learn better. In the code below, it is part of a user class. When I code using if/else blocks I format them like this...

if(!$this->isLoggedIn()){
    //do stuff
}

But in the code below it is more like this

if (! $this->isLoggedIn())
    return false;

Also in the function below you can see that there is a couple times that there can be a RETURN value. SO my question here, when RETURN is called, does it not run any code after that? Like does it end the script for that function there?

In this case if this is ran...

if (! $this->isLoggedIn())
        return false;

Does it continue to run the code below that?


Here is the function

<?PHP
private function logout($redir=true)
{
    if (! $this->isLoggedIn())
        return false;

    $this->obj->session->sess_destroy();

    if ($this->isCookieLoggedIn())
    {
        setcookie('user','', time()-36000, '/');
        setcookie('pass','', time()-36000, '/');
    }
    if (! $redir)
        return;

    header('location: '.$this->homePageUrl);
    die;
}
?>
like image 221
JasonDavis Avatar asked Jul 01 '26 04:07

JasonDavis


1 Answers

Yes.

When PHP sees a return command, it stops executing and returns it to whatever called it. This includes includes, function executions, method execution, etc.

In the following, 'Test' will never echo:

$test = "test";
return;
echo $test;

If you are in an included file, return will stop its execution, and the file that included it will finish executing.

One of the use cases is similar to what you described:

public function echoString($string)
{
    if(!is_string($string))
    {
        return;
    }
    echo $string;
}
like image 57
Tyler Carter Avatar answered Jul 03 '26 19:07

Tyler Carter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!