我知道你们中的一些人会假设接口或抽象,但这只能处理一些情况。这是他们打破的一个例子。
假设我们有实现相同接口并扩展相同基的类
class car extends fourwheeler implements ipaygas{
protected $tank1;
//interface
public function payGas($amount){}
}
class sportscar extends fourwheeler implements ipaygas{
protected $tank1;
protected $tank2;
//interface
public function payGas($amount){}
}
interface ipaygas{
function payGas($amount);
}
在某些情况下,您只需要一个接口,因为您可能只想执行“payGas()”。但是当你有条件满足的时候你会怎么做。
例如,如果 - 在支付汽油之前,您需要 (1) 检查车型,(2) 为跑车使用优质汽油,以及 (3) 为跑车的第二个油箱加满油。
这是我想做但做不到的
function pumpAndPay(iPayGas $car){
if(gettype($car) == "car"){
fillTank($car,(car) $car->tank1);
}else{
fillTank($car,(sportscar) $car->tank1);
fillTank($car,(sportscar) $car->tank2);
}
}
如何使用真实类型转换来做到这一点?在PHP中可以吗?
更新(基于响应):在我的“真实”案例中......想象我必须检查各种车辆类型,每种类型都有不同的油漆、车身、内饰、gas_type、cleaner_type、颜色等......
abstract class AVechicle{}
abstract class ACar extends AVechicle{}
abstract class ATruckOrSUV extends AVechicle{}
abstract class ABike extends AVechicle{}
class Car extends ACar{}
class SportsCar extends ACar{}
class SUV extends ATruckOrSUV{}
class Truck extends ATruckOrSUV{}
class Bike extends ABike{}
class Scooter extends ABike{}
class GasStation{
public function cleanVehicle(AVehicle $car){
//assume we need to check the car type to know
//what type of cleaner to use and how to clean the car
//if the car has leather or bucket seats
//imagine we have to add an extra $2/h for sports cars
//imagine a truck needs special treatment tires
//or needs inspection
}
public function pumpAndPay(AVehicle $car){
//need to know vehicle type to get gas type
//maybe we have a special for scooters only, Green Air campaign etc.
}
public function fullService(AVehicle $car){
//need to know if its a truck to do inspection FIRST
$this->cleanVehicle($car);
$this->pumpAndPay($car);
//bikes get 10% off
//cars get free carwash
}
}
仅接口和抽象只会走这么远......