Use Object-Oriented BCMath Extension in PHP 8.4

Use Object-Oriented BCMath Extension in PHP 8.4

PHP offers BCMath extension, which provides arbitrary precision arithmetic operations for working with large numbers. Since PHP 8.4, we can use object-oriented BCMath instead of functional. This new approach improves code readability and makes it easier to work with complex calculations.

Before PHP 8.4, the BCMath extension was used in a functional manner through a set of global functions such as bcadd, bcsub, bcmul, bcdiv, bccomp, etc.

<?php $num1 = '9223372036854775809'; $num2 = '9223372036854775808'; echo bcsub($num1, $num2); // 1 var_dump(bccomp($num1, $num2) === 1); // true

This functional approach worked well for straightforward calculations but could become cumbersome for complex operations involving multiple steps. It required careful tracking of arguments and often led to less readable code.

Since PHP 8.4, the BCMath extension can be used in the object-oriented manner by using the BcMath\Number class. This class allows the use of standard arithmetic operators (+, -, *, /) directly with BcMath\Number objects, simplifying mathematical operations. These objects are immutable, and they implement the Stringable interface, enabling seamless usage in string contexts like echo $num.

<?php use BcMath\Number; $num1 = new Number('9223372036854775809'); $num2 = new Number('9223372036854775808'); echo $num1 - $num2; // 1 var_dump($num1 > $num2); // true

This object-oriented approach simplifies code readability and allows for more intuitive handling of large numbers.

Leave a Comment

Cancel reply

Your email address will not be published.