Why do I need the brackets to add $a + $b
below:
<?php declare(strict_types=1);
function addNumbers(float $a, float $b) : int {
return (int)($a + $b);
}
echo addNumbers(1.2, 5.2);
?>
The used of brackets in cases like this confuses me. Why is an error thrown if the $a + $b
isn't surrounded by brackets? It may be a simple question but study material often doesn't explain detail. Any clarity would be appreciated.
Without the ()
around $a + $b
, the code is interpreted as
return ((int)$a) + $b;
because the operator precedence of (int)
is higher than that of +
(see the manual) which in this case would be
((int)1.2) + 5.2
=>
1 + 5.2
=>
6.2
Even though the first value in this expression is an int, because the second is a floating point number, PHP will perform type juggling and convert the first value to a float as well, thus the result of the expression is a floating point number, which cannot be returned by addNumbers
as it is declared to return an int
.
By putting the ()
in, the expression is interpreted as
(int)(1.2+5.2)
=>
(int)6.4
=>
6
which is ok to be returned.
As kenzotenma mentioned, "because you wanna typecast (int) the result of $a + $b
and not just $a
"
Try like below without bracket,
<?php declare(strict_types=1);
function addNumbers(float $a, float $b) : int {
$result = $a + $b;
return (int)$result ;
}
echo addNumbers(1.2, 5.2);
?>