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

如何在PHP5中动态调用子类方法?,php,oop,parent-child,Php,Oop,Parent Child,您只需调用$this->doSomething();在init()方法中 由于多态性,将根据子对象的类在运行时调用子对象的正确方法。您只需调用$this->doSomething();在init()方法中 由于多态性,将根据子对象的类在运行时调用子对象的正确方法 <?php class foo { //this class is always etended, and has some other methods that do utility work //and are

您只需调用$this->doSomething();在init()方法中


由于多态性,将根据子对象的类在运行时调用子对象的正确方法。

您只需调用$this->doSomething();在init()方法中

由于多态性,将根据子对象的类在运行时调用子对象的正确方法

<?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";
    }
}
?>
public function init() {
    $this->doSomething();
}

$obj = new bar();
$obj->doSomething(); // prints "bar"

$obj2 = new baz();
$obj->doSomething(); // prints "baz"