bernzkie
bernzkie

Reputation: 1269

return statement of function is not working as expected

I have 4 functions in my php script, which will access ascending order, at the last function i want to return a value, but the assignment isn't working.

My php script:

function fourth_f($var){
   $var = $var + 1;
   return $var; //this will make the $var = 6 and return to main process
}
function third_f($var){
   $var = $var + 1;
   fourth_f($var); //this will make the $var = 5
}
function second_f($var){
   $var = $var + 1;
   third_f($var); //this will make the $var = 4
}
function first_f($var_1, $var_2){  
   $var = $var_1 + $var_2 + 1;  
   second_f($var); //this will make the $var = 3
}

//The main
$var_1 = 1;
$var_2 = 1;
$final_var = first_f($var_1, $var_2);

//And i want to echo it here
echo $final_var;

When I execute the script, there's no error, but there's no result too, it's just blank, i'm expecting 6 as the result.

Anyone know what's wrong and how can I properly return a value from the last function?

Upvotes: 2

Views: 155

Answers (1)

Rizier123
Rizier123

Reputation: 59681

Your fourth function will return the value to the firth function. So you have to return each function call in each function, to then be able to assign the value to the variable, e.g.

function fourth_f($var){
   $var = $var + 1;
   return $var; //returns this value to function third_f
}
function third_f($var){
   $var = $var + 1;
   return fourth_f($var); //returns this value to function second_f
}
function second_f($var){
   $var = $var + 1;
   return third_f($var); //returns this value to function first_f
}
function first_f($var_1, $var_2){  
   $var = $var_1 + $var_2 + 1;  
   return second_f($var); //returns this value to the assignment
}

Upvotes: 2

Related Questions