如何用OOP实现链式计算?MyCalculator类调用兼容问题求助
问题分析与解决方案
你的代码核心矛盾在于:
add()和divideBy()当前返回的是浮点数值,单独用echo输出没问题,但链式调用时,数值类型无法调用对象方法(比如DivideBy)。- 若改成返回对象实例,单独
echo会输出对象而非计算结果。
同时原代码存在语法错误和逻辑bug:
- 属性声明行末尾多了逗号:
public float $a, $b, $c, - 构造函数内
new MyCalculator($this->c, 0)会触发无限递归(构造函数里实例化自身),直接导致内存溢出。 - 构造函数末尾缺少分号。
修正后的代码实现
通过让方法返回当前实例(支持链式调用),同时实现__toString()方法让实例能直接被echo输出计算结果,完美兼容两种调用方式:
class MyCalculator { public float $a, $b, $c; public function __construct(float $a, float $b) { $this->a = $a; $this->b = $b; $this->c = 0; // 初始化计算结果容器 } // 返回当前实例,支持链式调用 public function add(): self { $this->c = $this->a + $this->b; return $this; } // 返回当前实例,支持链式调用,增加除零判断避免报错 public function divideBy(float $num): self { if ($num === 0) { throw new InvalidArgumentException("除数不能为0"); } $this->c = $this->c / $num; return $this; } // 当echo实例时,自动返回计算结果的字符串形式 public function __toString(): string { return (string)$this->c; } // 可选:提供手动获取结果的方法 public function getResult(): float { return $this->c; } }
测试两种调用方式
1. 单独调用输出结果
$calc = new MyCalculator(12, 6); echo $calc->add(); // 输出:18
2. 链式调用输出结果
$calc = new MyCalculator(12, 6); echo $calc->add()->divideBy(3); // 输出:6
内容的提问来源于stack exchange,提问作者Max
相关产品推荐
相关产品推荐

