public function Fraction::add in Fraction 7
Add another fraction to this one.
Parameters
Fraction $fraction: Another fraction object to add to this one.
Return value
Fraction Returns this Fraction object.
File
- ./
fraction.class.inc, line 313 - Fraction class
Class
- Fraction
- @file Fraction class
Code
public function add(Fraction $fraction) {
// Get the numerator and denominator of each fraction.
$numerator1 = $this
->getNumerator();
$denominator1 = $this
->getDenominator();
$numerator2 = $fraction
->getNumerator();
$denominator2 = $fraction
->getDenominator();
// Calculate the sum of the two fractions.
// Use BCMath if available.
if (function_exists('bcmul') && function_exists('bcadd')) {
$denominator = bcmul($denominator1, $denominator2, 0);
$numerator = bcadd(bcmul($numerator1, $denominator2, 0), bcmul($numerator2, $denominator1, 0), 0);
}
else {
$denominator = $denominator1 * $denominator2;
$numerator = $numerator1 * $denominator2 + $numerator2 * $denominator1;
}
// Save the numerator and denominator.
$this
->setNumerator($numerator);
$this
->setDenominator($denominator);
return $this;
}