Jump to content

returning a variable from a function.


cloudll

Recommended Posts

I have just started using functions, and have been following a few tutorials. I think im misunderstanding returns.

 

lets say i have the variables called $math1 an $math2

 

and i want to make $total = $math1 + $math2;

 

i then use return $total;

 

I then thought i could echo $total and it would work outside of the function but its giving me an error of an underfines variable.

 

Could anyone explain what im doing wrong please? thanks

Link to comment
https://forums.phpfreaks.com/topic/255084-returning-a-variable-from-a-function/
Share on other sites

You're not quite understanding how it works.  Functions are completely self-contained.  Nothing outside the function knows anything about the contents of the function.  The variables and methods used inside the function do not exist outside the function.  Imagine that all your functions happen on another computer entirely.

 

So when you assign something to $total inside your function, it doesn't do anything outside your function.  Returning a value means that your function can be used in an assignment:

 

function doAdd($a, $b) {
  $total = $a + $b;
  return $total;
}

//won't work:
echo $total;

//won't work:
doAdd(1, 2);
echo $total;

//will work:
$total = doAdd(2, 3);
echo $total;

-Dan

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.