PHP Duck Sample - Head First - Design Patterns - Chapter One

后端 未结 4 1203
春和景丽
春和景丽 2021-01-16 16:03

This is the first question I ask from many others to come.

Someone here might call me crazy because I\'m following the mentioned book in the question\'s Title using

4条回答
  •  -上瘾入骨i
    2021-01-16 16:47

    The reason you are seeing Quack!
    output is because of this:

    class Quack implements QuackBehavior {
    
        public function quack() {
            echo 'Quack!
    '; } }

    Here's your problem: If you simply run new Quack(); the quack() method is automatically being executed by php as a constructor because it is the same name as your class. -- I see you referenced Java in your question, so this shouldn't be a foreign concept to you.

    new Quack(); // => Quack!

    A potentially better way

    color} wings\n";
      }
    
      public function quack(){
        echo "I'm quacking\n";
      }
    
      public function swim(){
        echo "I'm swimming\n";
      }
    }
    
    class Mallard extends Duck {
    
      public function __construct(){
        $this->color = "green";
      }
    
      public function quack(){
        echo "My quack sounds more like a honk\n";
      }
    }
    
    $m = new Mallard();
    $m->fly();
    $m->quack();
    $m->swim();
    
    ?>
    

    Output

    I'm flying with my green wings
    My quack sounds more like a honk
    I'm swimming
    

提交回复
热议问题