开启多参数功能

Switching on function with multiple parameters

当我有一个扩展 VehicleType

Car 实例时
abstract class VehicleType {

}

class Car extends VehicleType {

}


/**
 * @var VehicleType $vehicleType
 */
private $vehicleType;

并且 $vehicleType 变量可以是 VehicleType 的任何实例,我想像这样创建一个开关函数:

$vehicleType = new Car();

switch (is_a($vehicleType, get_class($vehicleType))) {
   ...
}

switch函数监听什么参数?我现在可以做这样的事情吗:

switch (is_a($vehicleType, get_class($vehicleType))) {
    case "Car": {
       //Its now a Car
    }
    case "Motorcyle": {
       //Its now a motorcycle
    }
    //etc
}

你需要这个:

switch (get_class($vehicleType))) { //it will get class name of $vehicleType
    case "Car": {   //match if $vehicleType is Car
       //Its now a Car
        break;
    }
    case "Motorcyle": {   //match if $vehicleType is Motorcyle
       //Its now a motorcycle
        break;
    }
    //etc
}

is_a returns 布尔值,因此您需要进行 if-else 检查。

像这样:

if (is_a($vehicleType, "Car")) {
    //It's now a Car
} else if (is_a($vehicleType, "Motorcyle")) {
    //It's now a motorcycle
} else {
    //It's something else
}