Should I use multiple classes for game?

前端 未结 5 1405
悲&欢浪女
悲&欢浪女 2020-12-14 23:24

I\'m considering making a text-based RPG-type program in PHP as both a holiday project and a chance to learn more about PHP and OOP. (Maybe not the best choice in language,

5条回答
  •  一整个雨季
    2020-12-14 23:40

    OOP lets you extend classes, reusing your the code. Here's a simple example. Check out the PHP docs for Inheritance.

    class Monster
    {
      public $size = 'average';
      public $color = 'grey';
    
      public function scare()
      {
        return "Bo!";
      }
    }
    
    class Rat extends Monster
    {
      public $size = 'small';
    
      public function scare()
      {
        return parent::scare() . " (runs away)";
      }
    }
    
    class Mouse extends Rat 
    {
      public $color = 'white';
    }
    

    And the output would be:

    $rat = new Rat();
    echo $rat->scare(); //output: Bo! (runs away)
    echo $rat->size;    //output: small
    echo $rat->color;   //output: grey
    

提交回复
热议问题