<?php
/**
* Immutable class for handling numbers with precision.
*
* Never change the $number or the $precision after the creation of the object.
*/
class DecimalNumber {
private $precision;
private $number;
/**
* Get an instance given a string and a precision
* @param string $string The decimal number in string form
* @param int $precision The precision of the number
* @return DecimalNumber Return new instance
*/
public static function string($string, $precision = 4) {
$me = get_called_class();
$number = new $me;
$number->precision = $precision;
$number->number = bcadd($string, '0', $precision);
return $number;
}
/**
* Perform an addition operation
* @param DecimalNumber $number the number to add
* @return DecimalNumber Return the sum
*/
public function sum(DecimalNumber $number) {
return DecimalNumber::string(bcadd($this->number, $number, $this->precision));
}
public function floored() {
return bcadd(bcadd($this->number, '0'), '0', $this->precision);
}
/**
* Automagically convert to a string
* @return string returns a string containing the value of this DecimalNumber
*/
public function __toString() {
return $this->number;
}
}
$d = DecimalNumber::string('4.7');
$c = $d->sum(DecimalNumber::string('2.1'));
echo $c->floored();
Output for 7.3.32 - 7.3.33, 7.4.26, 7.4.33, 8.0.13
Fatal error: Uncaught Error: Call to undefined function bcadd() in /in/QI4Kc:24
Stack trace:
#0 /in/QI4Kc(52): DecimalNumber::string('4.7')
#1 {main}
thrown in /in/QI4Kc on line 24
Process exited with code 255.
Output for 5.4.0 - 5.4.45
Fatal error: Call to undefined function bcadd() in /in/QI4Kc on line 24
Process exited with code 255.
Fatal error: Call to undefined function get_called_class() in /in/QI4Kc on line 20
Process exited with code 255.
Output for 4.4.2 - 4.4.9
Parse error: syntax error, unexpected T_STRING, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or '}' in /in/QI4Kc on line 10
Process exited with code 255.
Parse error: parse error, unexpected T_STRING, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or '}' in /in/QI4Kc on line 10
Process exited with code 255.
Output for 4.3.2 - 4.3.4
Parse error: parse error, expecting `T_OLD_FUNCTION' or `T_FUNCTION' or `T_VAR' or `'}'' in /in/QI4Kc on line 10
Process exited with code 255.