Jump to content

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.