<?php
class foo
{
//this class is always etended, and has some other methods that do utility work
//and are never overrided
public function init()
{
//what do to here to call bar->doSomething or baz->doSomething
//depending on what class is actually instantiated?
}
function doSomething()
{
//intentionaly no functionality here
}
}
class bar extends foo
{
function doSomething()
{
echo "bar";
}
}
class baz extends foo
{
function doSomething()
{
echo "baz";
}
}
?>
答案 0 :(得分:3)
你只需要拨打$ this-&gt; doSomething();在你的init()方法中。
由于多态性,将在运行时根据子类的类调用子对象的正确方法。
答案 1 :(得分:1)
public function init() {
$this->doSomething();
}
$obj = new bar();
$obj->doSomething(); // prints "bar"
$obj2 = new baz();
$obj->doSomething(); // prints "baz"