I have the following classes
- Abstract class duck
This class haveflyBehavoirof typeFlyBehavoir
Function to perform flyingpreformFly()
Function to setflyBehavoirsetFlyBrhavoir(FlyBehavoir $flyBehavoir) - Class DonaldDuck extends Duck
in this class, I have a__constructmethod, inside this constructor, I instantiate new fly behaviorFlyWithWings.
The problem is when I need to change flyBehavoir in the runtime via setFlyBrhavoir() method and set it to FlyWithRocket it does not change as long as flyBehavoir is private if I make it public it works fine. how can I do that?
thought that we can change any property in the superclass from the child class, as long as I access this private property vis setter.
below my attempt
<?php //abstract class that defines what it takes to be a duck //inside Duck we will have $flyBehavoir object of FlyBehavoir Type abstract class Duck{ private $flyBehavoir; public function preformFly(){ $flyBehavoir.fly(); } public function setFlyBehavoir(FlyBehavoir $flyBehavoir){ $this->flyBehavoir = $flyBehavoir; } } //creating type FlyBehavoir interface FlyBehavoir{ function fly(); } //this concrete class of type FlyBehavoir this will provide our ducks with the functionality they need to fly class FlyWithWings implements FlyBehavoir{ public function fly(){ echo "I am Flying with my own Wings<br>"; } } //this concrete class of type FlyBehavoir this will provide our ducks with the functionality they need to fly class FlyWithRocket implements FlyBehavoir{ public function fly(){ echo "I am the fastest duck ever, see my rockets wings <br>"; } } // creating our first duck and given it the ability to fly with wings class DonaldDuck extends Duck{ public function __construct(){ $this->flyBehavoir = new FlyWithWings; } } $donaldDuck = new DonaldDuck( ) ; $donaldDuck->flyBehavoir->fly(); //changing behavoir in run time $donaldDuck->setFlyBehavoir(new FlyWithRocket); $donaldDuck->flyBehavoir->fly(); Output I am Flying with my own Wings I am Flying with my own Wings
privatemeans… You wantprotectedinstead.