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

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

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.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.