Reputation: 48963
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;
}
?>
Upvotes: 3
Views: 1904
Reputation: 7930
As a side-note...
Even though the return
keyword can be used like this, many would consider using it in the manner it is used in your example function to be a very bad practice. It can mess with the "flow" of the code, making it less readable. (Similar to using the goto
statement, though admittedly not as bad.)
I would argue that the code you posted would be better structured like this:
<?php
function logout($redir=true)
{
if ($this->isLoggedIn())
{
$this->obj->session->sess_destroy();
if ($this->isCookieLoggedIn()) {
setcookie('user','', time()-36000, '/');
setcookie('pass','', time()-36000, '/');
}
if ($redir) {
header('location: '.$this->homePageUrl);
die;
}
}
}
?>
Nowhere in this version does the code "break" out of a block early. There is never any doubt as to whether the following lines should be executed or not.
Upvotes: 1
Reputation: 61567
Yes.
When PHP sees a return command, it stops executing and returns it to whatever called it. This includes include
s, 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;
}
Upvotes: 11
Reputation: 15118
I think we need to distinguish between return
used within a function and return
used globally.
As the PHP Function Reference says, script execution is only stopped in the second case.
@jason, you seemed to be asking about its use in a function.
Upvotes: 0