调用继承方法形式基类

时间:2014-05-20 01:26:52

标签: php inheritance

我有一个带有覆盖方法doSomething()的扩展类。 由于某种原因,继承的班级'方法永远不会只运行基础方法。

class cDemoClass {

  public static function getInstance() {
    static $instance = null;

    if ($instance === null)
      $instance = new cDemoClass();
    return $instance;
  } 

  private function __construct() {
  } 

  protected function doSomething() {
    echo 'do something';
  }

  public function call_me() {
    $this->doSomething();
  }
} 

class cDemoClassEx extends cDemoClass {

  protected function doSomething() {
    echo 'do something differently';
  }
}

$baseclass = cDemoClass::getInstance();
$baseclass->call_me();
echo '<br/>';
$extendedclass = cDemoClassEx::getInstance();
$extendedclass->call_me();

结果:

做点什么

做点什么

第二个应该是&#34;做一些不同的事情&#34;至少那是我所期待的。 谁能告诉我我做错了什么?感谢

3 个答案:

答案 0 :(得分:1)

因为cDemoClassEx::getInstance();仍在返回new cDemoClass();。您还必须覆盖getInstance()方法:

class cDemoClass {

  public static function getInstance() {
    static $instance = null;

    if ($instance === null)
      $instance = new cDemoClass();
    return $instance;
  } 

  private function __construct() {
  } 

  protected function doSomething() {
    echo 'do something';
  }

  public function call_me() {
    $this->doSomething();
  }
} 

class cDemoClassEx extends cDemoClass {
  public static function getInstance() {
    static $instance = null;

    if ($instance === null)
      $instance = new cDemoClassEx();
    return $instance;
  } 

  private function __construct() {
  } 

  protected function doSomething() {
    echo 'do something differently';
  }
}

$baseclass = cDemoClass::getInstance();
$baseclass->call_me();
echo '<br/>';
$extendedclass = cDemoClassEx::getInstance();
$extendedclass->call_me();

答案 1 :(得分:1)

在这种情况下,您需要使用late static binding(5.3+)。更改父方法getInstance行:

$instance = new cDemoClass(); 

$instance = new static();

你会得到:

do something
do something differently

在此处详细了解此功能:http://www.php.net/manual/en/language.oop5.late-static-bindings.php

答案 2 :(得分:0)

您必须使用cDemoClassEx :: getInstance()覆盖并更改此行

$instance = new cDemoClass();

$instance = new cDemoClassEx();

您还需要将cDemoClass::__construct()声明为protected,或者只需在cDemoClassEx中覆盖它。