为动物熊创建一个PHP类

时间:2018-05-24 13:25:15

标签: php

我正在寻找一种名为“熊”的CLASS方式:

  • 每隔2小时吃一次蜂蜜,记得他们上次吃蜂蜜的时间。
  • 决定是否需要睡觉。

我想知道有没有一种方法可以在不对数组时间进行硬编码的情况下进行此操作,而不是使用else语句来判断熊是否需要睡眠才能使单独的函数更好更清洁?     

class Bear

{

protected $name;
protected $currentTime;


public function setName($name)
{
   $this->name = $name;
}

public function getName()
{
   return $this->name;
}

public function showLastFeedtime()
{
   $lastFed = strtotime('-2 hour', strtotime($this->currentTime));

   $newdate = date('H:i', $lastFed);

   echo $this->name." last ate at ".$newdate."<br/><br/>";   
}

public function checkFeedingTime($checkHours = array())
{
   if(in_array($this->currentTime,$checkHours))
{
echo "It's ".$this->name."'s feeding time </br>";
echo "The time ".$this->currentTime. " is the time and I'm eating 
honey at right now. </br></br>";

echo "These are the times I eat</br>";

foreach($checkHours as $feedingTimes)
{
   echo $feedingTimes."</br>";    
}

echo "<hr>";

}
else
{
  //DECIDE IF THE BEAR NEEDS TO SLEEP
  echo "Barney is having a snooze";
}

}

public function getTime($currentTime)
{
   $this->currentTime = $currentTime;
}

public function setTime()
{
   return $this->currentTime;
}

}

//new instance of barney
$barney = new Bear();

//set the bears name
$barney->setName('Barney');

//get the bears name
$bigBear = $barney->getName();

//page info
echo "<h1>".$bigBear."'s profile page </h1>";
echo "<hr>";
echo "I am a bear and my name is {$bigBear} <br/>";
echo "<hr>";

//the current time
$currentTime = date('H:i');

$barney->getTime($currentTime);

//last feeding time
$barney->showLastFeedtime();

//ARRAY TIMES-barney eats every 2 hours
$checkHours = 
array('00:00','02:00','04:00','06:00','08:00',
'10:00','12:00','14:00','16:00','18:00','20:00','22:00');

//call the feeding time function
$barney->checkFeedingTime($checkHours);
?>

1 个答案:

答案 0 :(得分:1)

一些短课:

    <?php
// Ok, so we are in role of god and probably, we will want to create
// more animals than just bear, so we will prepare cheap interface for
// our creations
interface Animal {
    // we should be aware, if our lil beast is hungry
    public function isHungry(): bool;
    // and we should know, that we can feed it
    public function feed(): void;

    public function live(): void;

    public function isSleepy(): bool;

    public function sleep(): void;
}

class State {
    public $sleeping;
}

// Kay, now we can start with making our master beer
class Bear implements Animal {
    /**
     * He should have name
     * @var string
     */
    private $name;

    /**
     * We would like to know, when our bearsir was eating last time
     * @var \DateTime
     */
    private $lastEatingTime;

    /**
     * @var int 
     */
    private $energy;

    /**
     * @var State
     */
    private $state;

    // construction of bear, cause we can
    public function __construct(string $name, \DateTime $lastEatingTime)
    {
        $this->name = $name;
        $this->lastEatingTime = $lastEatingTime;
        $this->energy = 100;
        $state = new State();
        $state->sleeping = false;
        $this->state = $state;
    }
    // something like when you ask bear whats his name
    public function getName(): string
    {
        return $this->name;
    }
    // something like you get new bear and you wanna rename him
    public function setName(string $name): self
    {
        $this->name = $name;
        return $this;
    }
    // we have inteligent bear, so we can ask him about the last time of feeding
    public function getLastEatingTime(): \DateTime
    {
        return $this->lastEatingTime;
    }
    // we can also force him to think he ate before one minute even if its not true
    public function setLastEatingTime(\DateTime $lastEatingTime): self
    {
        $this->lastEatingTime = $lastEatingTime;
        return $this;
    }
    // we can determine if he is hungry or not by comparing current time and last time he ate
    public function isHungry(): bool
    {
        $now = new \DateTime();
        return $now->diff($this->getLastEatingTime())->format('%h') >= 2;
    }
    // give him food
    public function feed(): void
    {
        $this->energy += 5;
        $this->setLastEatingTime(new \DateTime());
    }

    public function isSleepy(): bool 
    {
        return $this->energy < 20;
    }

    /**
     * we will give him some rest
     */
    public function sleep(): void
    {
        $this->state->sleeping = true;
        $this->energy += rand(5, 20)/10;
        if ($this->energy >= 100) {
            $this->wakeUp();
        }
    }

    /**
     * Hey, wake up bear!
     */
    public function wakeUp(): void
    {
        $this->state->sleeping = false;
    }

    /**
     * Makes one lifecycle of bear
     */
    public function live(): void
    {
        $this->energy -= 1;
        if ($this->state->sleeping) {
            $this->sleep();
            echo 'Im sleeping';
        } else {
            echo 'Im awake and ';
            if ($this->isSleepy()) {
                echo 'Im sleepy, so i go sleep';
                $this->sleep();
            } else {
                if ($this->isHungry()) {
                    echo 'Im hungry, so im gonna eat some honey';
                    $this->feed();
                } else {
                    echo 'im fine';
                }
            }
        }
    }
}
// lets make life
class Life {
    public function live(Animal $animal)
    {
        // let life go on forever till some asteroid crashes our server
        while (true) {
            $animal->live();
            sleep(1);
        }
    }
}

$myBear = new Bear("Stanley", new \DateTime());
$life = new Life();
$life->live($myBear);