我是PHP和设计模式的开端。我一直在研究令人惊叹的Head First Design模式。所以,我一直在努力将原文翻译成PHP。但是,我必须做错事,因为它不起作用。你能救我吗?
<?php
interface FlyBehavior{
public function fly();
}
class FlyWithWings implements FlyBehavior{
public function fly(){
echo "I am flying!";
}
}
class FlyNoWay implements FlyBehavior{
public function fly(){
echo "I cannot fly!";
}
}
interface QuackBehavior{
public function quack();
}
class Quack implements QuackBehavior{
public function quack(){
echo "Quack";
}
}
class MuteQuack implements QuackBehavior{
public function quack(){
echo "Silence";
}
}
class Squeak implements QuackBehavior{
public function quack(){
echo "Squeak";
}
}
abstract class Duck{
protected $quackBehavior;
protected $flyBehavior;
public function performQuack(){
$this->$quackBehavior->quack();
}
public function performFly(){
$this->$flyBehavior->fly();
}
abstract public function display();
public function swim(){
echo "All ducks float, even decoy";
}
}
class MallardDuck extends Duck{
public function __construct(){
$this->quackBehavior=new Quack();
$this->flyBehavior=new FlyWithWings();
}
public function display(){
echo "I am real Mallard duck!";
}
}
$mallard=new MallardDuck();
$mallard->performQuack();
$mallard->performFly();
?>
当我跑步时,我在“$ this-&gt; $ quackBehavior-&gt; quack();”行中收到错误“Undefined variable:quackBehavior”在“抽象类鸭子”里面。
答案 0 :(得分:4)
错误说明了一切
public function performQuack(){
$this->$quackBehavior->quack();
}
public function performFly(){
$this->$flyBehavior->fly();
}
应该是
public function performQuack(){
$this->quackBehavior->quack();
}
public function performFly(){
$this->flyBehavior->fly();
}
$this->quackBehaviory
指的是您班级的财产。
$quackBehaviory
表示它是一个函数作用域变量。
因此,要访问class属性,您需要使用$this->quackBehaviory
答案 1 :(得分:2)
从$
和$this->$quackBehavior->quack();
移除$this->$flyBehavior->fly();
,即$quackBehavior
和$flyBehavior
应该是这样的....
$this->quackBehavior->quack(); //<--- Under your performQuack()
和
$this->flyBehavior->fly(); //<--- Under your performFly()