在此示例中,foreach将始终输出'I am Vehicle'
,而不会'I am Car'
或'I am Bus'
。
如何实现我获得与类类型相关的输出?
因此Car
应输出'I am Car'
,Bus
应输出'I am Bus'
等等。
class Vehicle {
public function getName(){
return 'I am Vehicle';
}
}
class Car extends Vehicle {
public function getName(){
return 'I am Car';
}
}
class Bus extends Vehicle {
public function getName(){
return 'I am Bus';
}
}
$vehicles = fetchAllVehicles();
foreach( $vehicles as $v){
echo $v->getName();
}