Fluent setters on child and parent Classes in PHP
Asked Answered
E

0

6

I am having some issues with the concept of fluent setters. I created 2 classes that extends from the same parent. And I put the common attributes between them in the parent class and I want to put the setters there , to avoid repeating the same code on each child class.

For example:

<?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;
    }
}

My problem is when I do this:

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

Is there any possibility that the parent return the $this referring to the child class? Or there is is a better way to do this?

Thanks!

Exhaust answered 10/11, 2016 at 0:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.