OOP Polymorphism and object creation at runtime

  oop, php, polymorphism

consider this code:

abstract class Vehicle {

abstract function drive();
public function honkTheHorn() {
    echo "beep beep!";
   }
}

class Car extends Vehicle {
    public function drive() {
        echo "car is driving";
    }
}

class Truck extends Vehicle {
    public function drive(){
        echo "Truck is driving";
    }
    
    public function blastTheHorn(){
        echo "big ass horn blast!!!";
    }
}

and then at some point of my code i need to create a Car or a Truck depending on some condition:

function doSomethingWithVehicle(Vehicle $vehicle){
    $vehicle->drive(); //this is fine
    $vehicle->honkTheHorn(); //this is fine as well
    $vehicle->blastTheHorn(); //this is not fine since it would work only if Truck needed
}

switch($someCondition){
    case 'need_car':
        $myVehicle = new Car();
        break;
    case 'need_truck':
        $myVehicle = new Truck();
        break;
}

doSomethingWithVehicle($myVehicle); 

How do I make this work? Is using a check on instanceof the only way to go? Is there a more OO way since using instanceof seems to be frowned upon? In this case it might be ok but what if I have many Vehicles? Also is there a way I coul avoid the switch statement?

Thanks for the help

Source: Ask PHP

LEAVE A COMMENT