0
<?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";
    }
}
?>
4

2 に答える 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 に答える