Jump to content

PHP Return Function


ldlonline

Recommended Posts

I just started PHP lessons and I have the following:

 

<?php

$a=5;

$b=8;

function add($a,$b) {

$total=($a+$b);

return $total;

}

echo "$a + $b = " . add($a,$b) . "<br />";

?>

 

What happens to the variable $total?  If I say echo $total it doesn't print anything. Why can't I say:

 

echo "$a + $b = $total";

 

?

 

Thanks in advance!

Link to comment
Share on other sites

Everything in the function stays in the function's private scope. $total is something that the function returns,

the total of $a and $b. Also, 'return $total' can be substituted for 'echo $total', they're just different structures.

<?php
$a=5; //Public variable, can be accessed here or in a function
$b=8;
function add($a,$b) {
$total=($a+$b); //Private, not public scope
return $total;
}
echo "$a + $b = " . add($a,$b) . "<br />";
?>

 

Link to comment
Share on other sites

The issue you are having is with what is called variable scope (google for more info). A variable created in a function is not available outside the function, unless you specify it as such. Personally, I would write your code like this

 

function add($a,$b)
{
    return ($a+$b);
}

$a=5;
$b=8;
$total = add($a, $b);
echo "$a + $b = $total<br />";

Link to comment
Share on other sites

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.