Most of the work I do is on a legacy app written procedurally. I'm beginning to convert pieces of it to OOP, and came across this example class used to add multiple times together:
At the bottom of the class, there is a public function called __toString()
, which appears to return some formatted text.
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));
}
}
The public static function fromString()
contains a return, and is how the class is called from a script. How does this class use __toString
? Why isn't the implode simply included in fromString()
?