Hi,
I am trying learn Object Oriented Programming in PHP. To do so I am going to try and rewrite using OOP a php script that I wrote previously. The script as input a series of rows of data, each row consisting of three variables - room name, width in metres and length in metres. It then outputs Those three values along with the area in metres and the width in feet and inches (eg 7’ 6’') and the length in feet and inches and the area in square metres (in the UK some realtors/estate agents give the dimensions in only metres but I find imperial units easier to visualise).
My first bit of code is to create the Class Room:
class Room{
public $width;
public $length;
public $roomName;
public function imperialWidth(){
$valInFeet = $this->width*3.2808399;
$valFeet = (int)$valInFeet;
$valInches = round(($valInFeet-$valFeet)*12);
return $valFeet."′ ".$valInches."″";
}
public function imperialLength(){
$valInFeet = $this->length*3.2808399;
$valFeet = (int)$valInFeet;
$valInches = round(($valInFeet-$valFeet)*12);
return $valFeet."′ ".$valInches."″";
}
}
I am able to pass values to the properties and and get values from the methods. But it seems to me that there is duplication that I should be able to overcome - the two methods that convert the metres into a string that reflects the imperial value are identical for length and for width apart from the fact that one uses the width and one uses the length. I think I should somehow be creating just one method and then passing different parameters to it, within the Room object? But I can’t figure out how to do this.
- Am I on the right track?
- How would I do this?
Thank you