Jump to content

Creating Class


puneet

Recommended Posts

Write a  class for feeding a horse. The Horse object should keep track of the last time it was fed and calculate when it is hungry. Assume there is another class that checks the horse every 10 minutes to see if it is hungry and if it is, it calls another method which feeds it. There should be about 3 methods on the class, but more can be added if needed. 

 

It's was question in my exam which I skipped

 

Can somebody hep me with that Please

 

Link to comment
Share on other sites

class Horse
{
     private fedtime;

     public function __construct()
     {
          $this->fedtime = new DateTime('yesterday');
     }

     public function getLastFedTime()
     {
          return $this->fedtime;
     }

     public function setLastFedTime($time)
          $this->fedtime = $time;
     }

     public function isHungry()
     {
          $now = new DateTime();
          $interval = date_diff($this->fedtime, $now);
          
          return $interval->format('%a') > 1; // gives true if the fedtime is more then one day ago, otherwise false.
     }

}
 

And now you do the rest!

Edited by Frank_b
  • Like 1
Link to comment
Share on other sites

class Horse
{
public function __construct(DateTime $lastFedAt) {
$this->lastFedAt = $lastFedAt;
}

public function feed() {
$this->lastFedAt = new DateTime();
}

public function isHungry() {
if (date('H') < 6 || date('H') > 22) {
return false; // sleeping
}
return time() - $this->lastFedAt->getTimestamp() > 4 * 3600; // feed every 4 hours
}
}

class HorseFeeder
{
public function check(Horse $horse) {
$horse->isHungry() && $horse->feed();
}

public function checkLoop(Horse $horse) {
while (true) {
$this->check($horse);
sleep(600);
}
}
Edited by ignace
Link to comment
Share on other sites

You skipped a class, a test no less, and you want someone here to write your answer for you.  SHAME ON YOU AND SHAME ON ANYONE HERE WHO GIVES YOU WHAT YOU ASK FOR.

He skipped the question on the test, probably couldn't answer it. Probably just trying to see what the answer was that was on the test. 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.