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
https://forums.phpfreaks.com/topic/170595-php-return-function/
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
https://forums.phpfreaks.com/topic/170595-php-return-function/#findComment-899811
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
https://forums.phpfreaks.com/topic/170595-php-return-function/#findComment-899812
Share on other sites

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.