views:

1462

answers:

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

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

$obj2 = new baz();
$obj->doSomething(); // prints "baz"
Owen
+2  A: 

You just have to call $this->doSomething(); in your init() method.

Due to polymorphism, the correct method of the child object will be called at runtime depending on the class of the child.

Franck