For a simple example, like the data in the question, it does not really make such a difference between using return
or echo
directly in the result. However, with the complexity of your application increasing, you will understand more easily. Let's first consider the example using echo
:
function soma($a, $b)
{
echo $a + $b;
}
When doing:
$x = 3;
$y = 8;
$res = soma($x, $y);
echo "A soma entre $x e $y é = $res";
Your result would be:
11
A soma entre 3 e 8 é =
That is, the value of the result was displayed before. It was already expected, since the result of the sum is already displayed at the time of the function call. You may think: ok, but we can do the following:
$x = 3;
$y = 8;
echo "A soma entre $x e $y é = ", soma($x, $y);
The result will be:
A soma entre 3 e 8 é = 11
Resolved.
For this example, yes, but now use the soma
function to calculate the following expression: 1 + 4 + 11. You can implement another function for this:
function soma3($a, $b, $c)
{
echo $a + $b + $c;
}
$x = 1;
$y = 4;
$z = 11;
echo "A soma entre $x, $y e $z é = ", soma3($x, $y, $z);
The result, in fact, will be:
A soma entre 1, 4 e 11 é = 16
But what if you need other expressions? For example, for 4 or 5 values, will you implement a function for each? Mathematically we know that to sum three values we can add the first two and the result to add with the third (associative property). That is, using the soma
function, but now with return
:
function soma($a, $b)
{
return $a + $b;
}
To analyze the expression 1 + 4 + 11, we can do:
$x = 1;
$y = 4;
$z = 11;
$res1 = soma($x, $y); // Faz $res1 = $x + $y
$res2 = soma($res1, $z); // Faz $res2 = $res1 + $z
echo "A soma entre $x, $y e $z é = $res2";
That the result will be exactly:
A soma entre 1, 4 e 11 é = 16
And if you need 4 values, type 2 + 3 + 5 + 7? No problems .
$x = 2;
$y = 3;
$z = 5;
$w = 7;
$res1 = soma($x, $y); // $res1 = $x + $y
$res2 = soma($z, $w); // $res2 = $z + $w
$res3 = soma($res1, $res2); // $res3 = $res1 + $res2;
echo "A soma entre $x, $y, $z e $w é = $res3";
And the result will be:
A soma entre 2, 3, 5 e 7 é = 17
That is, with only one function we can parse multiple expressions. Using echo
does not have this freedom (code reuse).