使用多个参数打开功能

时间:2015-01-13 13:48:12

标签: php polymorphism switch-statement

当我有Car个实例扩展VehicleType

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 (is_a($vehicleType, get_class($vehicleType))) {
    case "Car": {
       //Its now a Car
    }
    case "Motorcyle": {
       //Its now a motorcycle
    }
    //etc
}

2 个答案:

答案 0 :(得分:2)

你需要这个:

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
}

答案 1 :(得分:1)

is_a返回布尔值,因此您需要进行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
}