我正在尝试动态设置“setFlyBhavior(FlyBehavior $ newFlyBehavior)”。任何人都可以解释为什么它不能在下面的代码中工作?感谢您的帮助。
<?php
abstract class Duck {
public $flyBehavior;
public function performFly() {
return $this->flyBehavior->fly();
}
public function setFlyBhavior(FlyBehavior $newFlyBehavior) {
$this->flyBehavior = $newFlyBehavior;
}
}
interface FlyBehavior {
public function fly();
}
class GotWings implements FlyBehavior {
public function fly(){
return "<br />I'm flying with wings!!<br />";
}
}
class NotWings implements FlyBehavior {
public function fly(){
return "<br />I can't fly I have no wings!!<br />";
}
}
class FlyingDuck extends Duck {
public function __construct(){
$this->flyBehavior = new GotWings();
}
}
$ducky = new FlyingDuck();
// Code works when the setFlyBehavior function is commented out.
$ducky->setFlyBehavior(new NoWings);
echo "<br />I'm a Duck: " . $ducky->performFly();
?>
注意:代码在不调用“ducky-&gt; setFlyBehavior函数时有效。我也尝试在不使用类型转换的情况下在Duck类中定义setFlyBehavior函数,但也失败了。”
public function setFlyBhavior($newFlyBehavior) {
$this->flyBehavior = $newFlyBehavior;
}
答案 0 :(得分:0)
您正在调用错误的函数和类名。
替换行:
$ducky->setFlyBehavior(new NoWings);
使用:
$ducky->setFlyBhavior(new NotWings);