Google News
logo
PHP program to create a class to add two times
In the following example of PHP program to create a class to add two times :
Program :
<?php
class Time {
    private $hours;
    private $minutes;
    private $seconds;

    public function __construct($hours, $minutes, $seconds) {
        $this->hours = $hours;
        $this->minutes = $minutes;
        $this->seconds = $seconds;
    }

    public function addTime($time) {
        $this->hours += $time->hours;
        $this->minutes += $time->minutes;
        $this->seconds += $time->seconds;

        if ($this->seconds >= 60) {
            $this->minutes += (int) ($this->seconds / 60);
            $this->seconds %= 60;
        }

        if ($this->minutes >= 60) {
            $this->hours += (int) ($this->minutes / 60);
            $this->minutes %= 60;
        }
    }

    public function __toString() {
        return sprintf("%02d:%02d:%02d", $this->hours, $this->minutes, $this->seconds);
    }
}

$time1 = new Time(3, 45, 30);
$time2 = new Time(1, 30, 15);

$time1->addTime($time2);

echo "Time 1 + Time 2 = $time1\n";
?>
Output :
Time 1 + Time 2 = 05:15:45
In this program, we define a `Time` class with three private attributes: `$hours`, `$minutes`, and `$seconds`. The constructor takes three arguments to set these attributes.

We also define a public method `addTime` that takes another `Time` object as an argument and adds its values to the current object's values. We perform some checks to ensure that the values stay within their respective ranges (e.g., 0-59 for minutes and seconds).

Finally, we define a magic method `__toString` that returns a string representation of the `Time` object in the format `hh:mm:ss`.

We create two `Time` objects, add them together using the `addTime` method, and then print out the result using the `echo` statement.