如何确保在PHP中具有父实例时运行子方法

时间:2016-10-01 13:13:01

标签: php inheritance polymorphism

在此示例中,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();
}

0 个答案:

没有答案