如何在PHP 5中动态调用子类方法?

时间:2008-11-20 03:29:35

标签: php oop parent-child

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

2 个答案:

答案 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"