PHP program to create a class to add two distances

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

Add Two Distances using Class

Here, we will create a Distance class that contains feet and inches and then we add two distances using Distance class.

PHP code to add two distances using class

The source code to add two distances is given below. The given program is compiled and executed successfully.

//PHP program to add two distances.
class Distance
    // Properties
    private $feet;
    private $inch;

    function SetDist($f, $i)
        $this->feet = $f;
        $this->inch = $i;

    function PrintDist()
        print ("Feet  : " . $this->feet . '<br>');
        print ("Inchs : " . $this->inch . '<br><br>');

    function AddDist(Distance $d2)
        $temp = new Distance();

        $temp->feet = $this->feet + $d2->feet;
        $temp->inch = $this->inch + $d2->inch;

        if ($temp->inch >= 12)
            $temp->inch -= 12;
        return $temp;

$d1 = new Distance();
$d1->SetDist(10, 2);
print ("Distance1 : " . '<br>');

$d2 = new Distance();
$d2->SetDist(10, 3);
print ("Distance2 : " . '<br>');

$d3 = $d1->AddDist($d2);
print ("Distance3 : " . '<br>');



Distance1 :
Feet : 10
Inchs : 2

Distance2 :
Feet : 10
Inchs : 3

Distance3 :
Feet : 20
Inchs : 5


In the above program, we created a class Distance that contains data members feet and inch. The Distance class contains three member functions SetDist(), PrintDist(), and AddDist().

The SetDist() function is used to set the values in the data member's feet and inch. The PrintDist() function is used to print the values of data members.

The AddDist() method is used to add the distance of the current object with the specified object and return the object that contains the addition of distance.

Here, we created two objects $d1 and $d2. Then add both distances using AddDist() function and assign the addition of distances in the object $d3.

PHP Class & Object Programs »

Related Programs

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.