【问题标题】:How to dynamically call child class methods in PHP 5?如何在 PHP 5 中动态调用子类方法?
【发布时间】:2008-11-20 03:29:35
【问题描述】:
<?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";
    }
}
?>

【问题讨论】:

    标签: php oop parent-child


    【解决方案1】:

    你只需要调用 $this->doSomething();在你的 init() 方法中。

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

    【讨论】:

      【解决方案2】:
      public function init() {
          $this->doSomething();
      }
      
      $obj = new bar();
      $obj->doSomething(); // prints "bar"
      
      $obj2 = new baz();
      $obj->doSomething(); // prints "baz"
      

      【讨论】:

        猜你喜欢
        • 2010-09-21
        • 2010-09-20
        • 2014-07-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-13
        相关资源
        最近更新 更多