我所做的大部分工作都是在程序上编写的遗留应用程序上。我开始将它的一部分转换为 OOP,并遇到了这个用于多次相加的示例类:
在类的底部,有一个名为 的公共函数__toString()
,它似乎返回一些格式化的文本。
class Duration
{
/*
$d1 = Duration::fromString('2:22');
$d1->add(Duration::fromString('3:33'));
echo $d1; // should print 5:55
*/
public static function fromString($string)
{
$parts = explode(':', $string);
$object = new self();
if (count($parts) === 2) {
$object->minutes = $parts[0];
$object->seconds = $parts[1];
} elseif (count($parts) === 3) {
$object->hours = $parts[0];
$object->minutes = $parts[1];
$object->seconds = $parts[2];
} else {
// handle error
}
return $object;
}
private $hours;
private $minutes;
private $seconds;
public function getHours() {
return $this->hours;
}
public function getMinutes() {
return $this->minutes;
}
public function getSeconds() {
return $this->seconds;
}
public function add(Duration $d) {
$this->hours += $d->hours;
$this->minutes += $d->minutes;
$this->seconds += $d->seconds;
while ($this->seconds >= 60) {
$this->seconds -= 60;
$this->minutes++;
}
while ($this->minutes >= 60) {
$this->minutes -= 60;
$this->hours++;
}
}
public function __toString() {
return implode(':', array($this->hours, $this->minutes, $this->seconds));
}
}
公共静态函数fromString()
包含一个返回值,并且是从脚本调用该类的方式。这个类如何使用__toString
?为什么内爆不简单地包含在 中fromString()
?