mercredi 29 juillet 2020

Declaration not compatible with interface (PHP)

Let's say I have one parent class with two child classes like this

abstract class Vehicle {
    public function setManufacturer(string $manufacturer) { ... }
}

class Bicycle extends Vehicle {
    public function addSaddle() { ... }
}

class Car extends Vehicle {
    public function setSpeedLimit(float $limit) { ... }
}

Now I want to use these objects with an interface like this

interface VehicleInterface {
    public function create(Vehicle $vehicle);
}

class BicycleService implements VehicleInterface {
    public function create(Bicycle $bicycle) {
        $bicycle->setManufacturer('Some company'); // Common for all Vehicle objects
        $bicycle->addSaddle(); // Common only for Bicycle objects
    }
}

It seems that this is not possible since BicycleService create(...) is not compatible with the interface. Is there any way around this other than removing type hints?

Aucun commentaire:

Enregistrer un commentaire