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

后端 未结 4 1201
春和景丽
春和景丽 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条回答
  • 2021-01-16 16:32

    It is because when you have the class with the same name of the method, the PHP consider it as a constructor. This is already deprecated in php 7 and it will be discontinued soon. You can see it on the online documentation: http://php.net/manual/en/migration70.deprecated.php

    0 讨论(0)
  • 2021-01-16 16:47

    The reason you are seeing Quack!<br /> output is because of this:

    class Quack implements QuackBehavior {
    
        public function quack() {
            echo 'Quack!<br />';
        }
    }
    

    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!<br />
    

    A potentially better way

    <?php
    
    interface CanFly {
      public function fly();
    }
    
    interface CanQuack {
      public function quack();
    }
    
    abstract class Duck implements CanFly, CanQuack {
    
      protected $color = "DEFAULT"
    
      public function fly(){
        echo "I'm flying with my {$this->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
    
    0 讨论(0)
  • 2021-01-16 16:51

    In your situation, I would personally assume that I've overlooked something when saying that an echo is being reached in the code without a call to that method. I can't see a way that this would be possible.

    Reanalyze your code and look for a sneaky way that your echo 'Quack!quack!' is being reached.

    0 讨论(0)
  • 2021-01-16 16:52

    Comment this line:

    echo 'Quack!<br />';
    

    Do you see any more quacks? If so, then there is an echo/exit/die in your code with this string!

    0 讨论(0)
提交回复
热议问题