1. 程式人生 > 其它 >php BCmath 封裝類

php BCmath 封裝類

<?php
/**
 * BCmath 封裝類
 * Calc::init(10)->add(1,2,3)->sub(1,2)->mul(4, 5)->value(2); // (10+1+2+3-1-2)*4*5 最後 get 保留 2位小數
 * Calc::add(10, 2)->div(2)->value(2);
 */
namespace App\Helpers;

/**
 * @method \App\Helpers\Calc add(number ...$value) 加法
 * @method \App\Helpers\Calc sub(number ...$value) 減法
 * @method \App\Helpers\Calc mul(number ...$value) 乘法
 * @method \App\Helpers\Calc div(number ...$value) 除法
 * @method \App\Helpers\Calc comp(number ...$value) 比較
 * @method \App\Helpers\Calc mod(number ...$value) 取模
 * @method \App\Helpers\Calc pow(number ...$value) 乘方
 * @method \App\Helpers\Calc sqrt(number ...$value) 開方
 
*/ class Calc { protected $init = 0; protected $carry = []; public function __construct($value = 0) { $this->init = $value; } public static function init($value = 0) { return new static($value); } public static function __callStatic($method, $args
) { return self::init(array_shift($args))->$method(...$args); } public function __call($method, $args) { $this->carry[] = ['bc' . $method => $args]; return $this; } /** * 獲取值 * @param int $scale 保留小數位 * @return int */ public
function value($scale = 2) { foreach($this->carry as $item){ foreach($item as $func => $value){ $this->init = array_reduce($value, function($carry, $val) use($func, $scale){ return $func($carry, $val, $scale); }, $this->init); } } return $this->init; } }