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
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
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 />
<?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
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.
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!