<?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";
}
}
?>
问问题
3267 次
2 回答
3
你只需要调用 $this->doSomething(); 在您的 init() 方法中。
由于多态性,子对象的正确方法将在运行时根据子对象的类被调用。
于 2008-11-20T03:33:56.253 回答
1
public function init() {
$this->doSomething();
}
$obj = new bar();
$obj->doSomething(); // prints "bar"
$obj2 = new baz();
$obj->doSomething(); // prints "baz"
于 2008-11-20T03:33:46.533 回答