【问题标题】:How to call parent's method which is overloaded in child如何调用子级重载的父级方法
【发布时间】:2013-06-20 10:11:04
【问题描述】:

我有 PHP 代码

<?
class AParent {

  function to_s() {
    return $this->id;
  }

}

class AChild {

  public $id;
  public $name;

  function to_s() {
    if(!empty($this->name)) {
      $ret = $this->name;
    } else {
      $ret = /** call parent's method to_s() */
    }
    return $ret;
  }

}

如何调用子级重载的父级方法? :) 可以使用静态方法,但是如何使用非静态方法呢?

$a = new AChild();
$a->id = 1;
$a->name = 'Something';
echo $a; // Should echo "Something"

$b = new AChild();
$b->id = 2;
echo $b; // Should echo "2"

【问题讨论】:

  • 附注:您可以将 public $id; 声明移至 AParent 类。

标签: php class parent superclass super


【解决方案1】:

用$ret = parent::to_s()就够了

【讨论】:

    猜你喜欢
    • 2015-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-03
    • 1970-01-01
    • 2019-03-01
    • 2019-04-07
    相关资源
    最近更新 更多