dqypcghd381390 2018-05-24 13:25
浏览 184
已采纳

为动物熊创建一个PHP类

I'm looking for a way of a single CLASS named "Bear" to be able to:

  • Eat honey every 2 hours and remember when they last had honey.
  • Decide if they need to sleep.

I want to know is there a way of doing this without hard coding the array times and rather than using an else statement to decide if the bear needs to sleep would a separate function be better and cleaner?

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条回答 默认 最新

  • dongqixian8474 2018-05-24 13:46
    关注

    Some short class:

        <?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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题