Как динамически вызывать методы дочернего класса в PHP 5? - PullRequest
0 голосов
/ 20 ноября 2008
<?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 ]

3 голосов
/ 20 ноября 2008

Вам просто нужно вызвать $ this-> doSomething (); в вашем методе init ().

Из-за полиморфизма правильный метод дочернего объекта будет вызываться во время выполнения в зависимости от класса дочернего объекта.

1 голос
/ 20 ноября 2008
public function init() {
    $this->doSomething();
}

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

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