【发布时间】:2019-01-30 22:04:49
【问题描述】:
我有以下课程
-
抽象类鸭子
此类具有flyBehavoir类型的FlyBehavoir
执行飞行的功能preformFly()
设置flyBehavoirsetFlyBrhavoir(FlyBehavoir $flyBehavoir)的函数 -
类 DonaldDuck 扩展了 Duck
在这个类中,我有一个__construct方法,在这个构造函数中,我实例化了新的飞行行为FlyWithWings。
问题是,当我需要在运行时通过setFlyBrhavoir() 方法更改flyBehavoir 并将其设置为FlyWithRocket 时,只要flyBehavoir 是私有的,如果我将其公开,它就不会更改它工作正常。我该怎么做?
认为我们可以从子类更改超类中的任何属性,只要我访问这个私有属性 vis setter。
低于我的尝试
<?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
【问题讨论】:
-
除非我误解了问题,否则您在问题中已经提到了解决方案:您需要使用setter而不是直接访问属性。
-
这就是
private的意思……你想要的是protected。 -
使用公共/受保护而不是私有。
-
jeroen 如果你检查代码,我正在使用 setter,
-
deceze protected give another error (!) 致命错误:未捕获的错误:无法访问 /home/yazfarqj/dev/headFirstDesignPatrenBook/ch1/duck3.php 中的受保护属性 DonaldDuck::$flyBehavoir 第 48 行