DanielTheRocketMan
DanielTheRocketMan

Reputation: 3249

Strategy pattern not working: What am I doing wrong?

I am a very beginning in PHP and Design Patterns. I have been studying the amazing Head First Design patterns. So, I have been trying to translate the original to PHP. However, I must be doing things very wrong, because it is not working. Can you help me?

<?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();


?>

When I run I get the error "Undefined variable: quackBehavior" in line "$this->$quackBehavior->quack();" inside "abstract class Duck".

Upvotes: 0

Views: 74

Answers (2)

Abhik Chakraborty
Abhik Chakraborty

Reputation: 44864

The error says it all

public function performQuack(){
        $this->$quackBehavior->quack();
    }    

    public function performFly(){
        $this->$flyBehavior->fly();
    }

should be

public function performQuack(){
        $this->quackBehavior->quack();
    }    

    public function performFly(){
        $this->flyBehavior->fly();
    }

$this->quackBehaviory refers to a property of your class.

$quackBehaviory means that it's a function scoped variable.

So to access the class property you need to use $this->quackBehaviory

Upvotes: 4

Remove the $ from $this->$quackBehavior->quack(); and $this->$flyBehavior->fly(); i.e. infront of $quackBehavior and $flyBehavior

Should be like this....

 $this->quackBehavior->quack(); //<--- Under your performQuack()

and

 $this->flyBehavior->fly(); //<--- Under your performFly()

Upvotes: 2

Related Questions