PHP program to create a class to subtract one distance from another distance

Here, we are going to learn how to create a class to subtract one distance from another distance in PHP?
Submitted by Nidhi, on November 11, 2020

Here, we will create a Distance class that contains feet and inches and then we subtract one distance from other distance using Distance class.

Program/Source Code:

The source code to subtract one distance from another distance is given below. The given program is compiled and executed successfully.

<?php
//PHP program to subtract one distance from other distance.
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 SubDist(Distance $d2)
    {
        $temp = new Distance();

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

        if ($temp->inch < 0)
        {
            $temp->feet--;
            $temp->inch = 12 + $temp->inch;
        }
        return $temp;
    }
}

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

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

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

?>

Output:

Distance1 :
Feet : 10
Inchs : 2

Distance2 :
Feet : 6
Inchs : 3

Distance3 :
Feet : 3
Inchs : 11

Explanation:

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 SubDist().

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 SubDist() method is used to subtract a specified distance from the current object and return the object that contains the subtraction of distances.

Here, we created two objects $d1 and $d2. Then calculated the subtraction of distances using SubDist() function and assign the subtraction of distances in the object $d3.






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.