当我有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
}
答案 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
}