Reputation: 93
I am trying to understand the return
keyword and its functionality, however, I am getting a little confused.
I have read this which has been a good starting point, but I can't seem to understand the solution to what I imagine is a very simple problem.
Say I have a PHP file called index.php and I call a function from it like so (imagine it's not being called from within a class or function);
echo $fun -> editAnswer ($obj->answer_id, $obj->answerString ,$obj->correct, $questionID, $lecturer_id);
Then in my function.php I have:
public function editAnswer($answer_id, $answerString, $correct, $questionID, $lecturer_id){
$db = $this -> db;
if (!empty ($answer_id) && !empty ($answerString) && !empty($correct) && !empty($questionID) && !empty ($lecturer_id)){
$result = $db -> editAnswer($answer_id, $answerString, $correct, $questionID, $lecturer_id);
if ($result) {
return "The Updates To Your Answer Have Been Saved!";
} else {
$response["result"] = "failure";
$response["message"] = "The Updates To Your Answer Have Not Been Saved, Please Try Again";
return json_encode($response);
}
} else {
return $this -> getMsgParamNotEmpty();
}
}
If successful, I will return the string The Updates To Your Answer Have Been Saved!
, however, this will be immediately echoed to the screen of index.php.
My thinking is that if after calling the function, the user was still on index.php, it might look a little ugly to have a string at the top of the page. Maybe I would want to catch the returned string and then create an alert dialog before displaying it.
How would I go about doing something like that rather than immediately echoing the returned string?
Upvotes: 1
Views: 1007
Reputation: 1130
The return value is echoed because you use echo
to output the result.
Save the result to a variable and use it later
$result = $fun -> editAnswer ($obj->answer_id, $obj->answerString ,$obj->correct, $questionID, $lecturer_id);
echo "we called the function"
echo "the result was $result"
Upvotes: 1