当我用面向对象编程时,我遇到了这个问题。在这个例子中,我的意思是创建一个有名字和体重的健身房成员,他在特定的时间内锻炼,然后减肥。不幸的是,重量对象在运动之后不会更新。
当我var_dump()健身房成员对象后,计算出的体重仍然是78,即使它符合减肥的标准。
以下是代码:
重量等级:
class Weight
{
protected $weight;
public function __construct($weight)
{
$this->weight = $weight;
}
public function gain($kilograms)
{
return new static($this->weight + $kilograms);
}
public function loose($kilograms)
{
return new static($this->weight - $kilograms);
}
}体育课成员:
class GymMember
{
protected $name;
protected $weight;
public function __construct($name, Weight $weight)
{
$this->name = $name;
$this->weight = $weight;
}
public function workoutFor(TimeLength $length)
{
if(!$length->inSeconds() > (40 * 60 ))
{
return 'Keep up the good work!';
}
$this->weight->loose(2);
}
}新成员编制如下:
$gymMember = new GymMember('MTROBERT', new Weight(78));
$gymMember->workOutFor(Timelength::minutes(45));
var_dump($gymMember);发布于 2018-09-21 08:44:09
您的“丢失”和“增益”方法正在返回一个新的Weight对象,但是您的GymMember没有这样做:
public function workoutFor(TimeLength $length)
{
// ...
$this->weight->loose(2);
}因为lost (切切:“lost”,而不是“ lose ”)方法返回一个新对象,而不是修改自己,而且您没有将返回值分配给任何东西,所以它就是丢失了。
有两种可能的解决办法:
更改GymMember::workout(),这样它就可以执行如下操作:
$this->weight = $this->weight->loose(2);或者更改Weight::lose(),这样它就可以做一些事情:
public function lose($kilograms)
{
$this->weight -= $kilograms;
}这两种方法都能解决你的问题。
https://stackoverflow.com/questions/52439130
复制相似问题