PHP program to create a class to add two times

Here, we are going to learn how to create a class to add two times in PHP?
Submitted by Nidhi, on November 11, 2020 [Last updated : March 13, 2023]

Add Two Times using Class

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

PHP code to add two times using class

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

//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: ");



Time after addition: 18:33:3


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.

PHP Class & Object Programs »

Related Programs

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.