PHP中的子类和父类的流畅的setter

时间:2016-11-10 00:12:32

标签: php fluent-interface

我对流利的制定者的概念有一些问题。我创建了两个从同一个父级扩展的clases。我将它们之间的公共属性放在父类中,我想将setter放在那里,以避免在每个子类上重复相同的代码。

例如:

<?php
class Vehicle {
    protected $color;
    protected $wheels;

    public function setColor($color) { 
        $this->color = $color;
        return $this;
    }

    public function setWheels($wheels) { 
        $this->wheels = $wheels;
        return $this;
    }
}

class Motorbike extends Vehicle {
    protected $engine;

    public function setEngine($engine) { 
        $this->engine = $engine;
        return $this;
    }
}

class Bike extends Vehicle {

}

我的问题是当我这样做时:

$motorbike = new Motorbike();
$motorbike->setColor('blue') 
->setEngine(4.2) // Here the returned '$this' referes to the parent class Vehicle, so the setEngine doesnt' exist.
->setWheels(4)

父母是否有可能将$ this引用给子类?或者有更好的方法吗?

谢谢!

0 个答案:

没有答案