PHP 的 值对象
等级 5296 次按键
创建一个Money值对象,其add()不修改现有对象,而是返回新对象。
PHP 代码
// 值对象:以分为单位保存金额1class Money { // 用整数的分来避免浮点数舍入误差2 public function __construct(3 private int $cents4 ) {}5 // 返回新的Money,$this保持不变6 public function add(Money $m): Money {7 return new Money( // 可以访问同一类其他对象的私有成员8 $this->cents + $m->cents9 );10 }11 // 把金额格式化为美元12 public function fmt(): string { // 3100 / 100得到整数31,因此不显示小数13 return "$" . ($this->cents / 100);14 }15}16 // 10.50美元和20.50美元17$a = new Money(1050);18$b = new Money(2050);// 1050 + 2050 = 3100分,输出$3119echo $a->add($b)->fmt();运行结果
$31
可以用这段代码练习打字。成绩不会计入排行榜。
这段代码中的符号
这段 PHP 代码中需要输入的符号及其出现次数。
$× 10(× 9)× 9-× 5;× 5>× 5{× 4}× 4_× 2:× 2