Q:

PHP program to create a class to add two times

belongs to collection: PHP Classes & Objects Programs

0

Here, we will create a Time class that contains hours, Minutes, and Seconds and then we add two times.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

The source code to create a class to add two times is given below. The given program is compiled and executed successfully.

<?php
//PHP program to create a class to add two times.
class Time
{
    // Properties
    private $hours;
    private $minutes;
    private $seconds;

    function SetTime($h, $m, $s)
    {
        $this->hours = $h;
        $this->minutes = $m;
        $this->seconds = $s;
    }

    function PrintTime()
    {
        print ((int)$this->hours . ":" . $this->minutes . ":" . $this->seconds . '<br><br>');
    }

    function AddTimes(Time $T1, Time $T2)
    {
        $this->seconds = $T1->seconds + $T2->seconds;
        $this->minutes = $T1->minutes + $T2->minutes + $this->seconds / 60;;

        $this->hours = $T1->hours + $T2->hours + ($this->minutes / 60);
        $this->minutes %= 60;
        $this->seconds %= 60;
    }
}

$T1 = new Time();
$T1->SetTime(10, 5, 24);

$T2 = new Time();
$T2->SetTime(8, 27, 39);

$T3 = new Time();

$T3->AddTimes($T1, $T2);
print ("Time after addition: ");
$T3->PrintTime();

?>

Output:

Time after addition: 18:33:3

Explanation:

In the above program, we created a class Time that contains data members hours and Minutes. The Distance class contains three member functions SetTime()PrintTime(), and AddTime().

The SetTime() function is used to set the values in the data members. The PrintTime() function is used to print the values of data members.

The AddTime() method is used to add two times. Here, we created two objects $T1 and $T2. Then add two times using AddTime() function and assign the addition of times in the object $T3.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

PHP Classes & Objects Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
PHP program to convert seconds into hours, minutes... >>
<< PHP program to create a class to subtract one dist...