For a simple example, as given in the question, it doesn’t really make such a difference between using the return
or the echo
directly in the result. However, with the complexity of your application increasing, you’ll understand more easily. Let’s consider first the example using echo
:
function soma($a, $b)
{
echo $a + $b;
}
In doing:
$x = 3;
$y = 8;
$res = soma($x, $y);
echo "A soma entre $x e $y é = $res";
Its result would be:
11
A soma entre 3 e 8 é =
That is, the result value was displayed before. It was already expected, because the sum result is already displayed at the time of the function call. You might think, okay, but here’s what we can do:
$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
Solved.
For this example, yes, but now use the function soma
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 add up three values we can add up the first two and the result add up with the third (associative property). That is, using the function soma
, 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 needed for 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 analyze multiple expressions. Using the echo
we do not have this freedom (code reuse).
Thanks Anderson, now yes I understand!
– Lucas de Carvalho