If called from within a function, the return statement immediately ends execution of the current function, and returns its argument as the value of the function call.
Quoted from php manual: http://php.net/manual/en/function.return.php
So if I were to write this function:
public function check_db_for_desired_value()
{
//...connect to db, prepare stmt, etc.
while (mysqli_stmt_fetch($stmt))
{
if($column == 'desired_value')
{
return TRUE;
}
else
{
return FALSE;
}
}
// these commands would never get executed
mysqli_stmt_free_result($stmt);
mysqli_stmt_close($stmt);
mysqli_close($link);
}
So (if what is says in the php manual is correct) my results get never freed, my stmt never gets closed and my db connection stays open, because I returned something and ended execution of the function...
So should I instead of returning something set the value of a variable and then return this value after closing everything?
I ask, because my code is working and I dont get any errors, eventhough I have written functions like this before...
You are correct, nothing is executed after a return
.
But you can use __destruct
to close connections and clear results:
function __destruct() {
mysqli_stmt_free_result($this->stmt); // making $stmt a variable inside class
mysqli_stmt_close($this->stmt);
mysqli_close($this->link);
}
The destructor method will be called as soon as there are no other references to a particular object, or in any order during the shutdown sequence. - PHP.NET
Otherwise you should move the freeing and closing before return
is called.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With