tcxbalage
tcxbalage

Reputation: 726

Calling inherited method form base class

I have an extended class with an overriden method doSomething(). For some reason the inherited class' method never runs only the base one.

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();

result:

do something

do something

The second one should be "do something differently" at least that's what I'm expecting. Can anyone tell me what I'm doing wrong? Thanks

Upvotes: 0

Views: 60

Answers (3)

voodoo417
voodoo417

Reputation: 12111

In this case, you need using late static binding (5.3+). Change in parent method getInstance line :

$instance = new cDemoClass(); 

to

$instance = new static();

You will get:

do something
do something differently

Read more about this feature here: http://www.php.net/manual/en/language.oop5.late-static-bindings.php

Upvotes: 1

shinkou
shinkou

Reputation: 5154

You have to override with the cDemoClassEx::getInstance() and change this line

$instance = new cDemoClass();

into

$instance = new cDemoClassEx();

You will also need to declare the cDemoClass::__construct() as protected or simply override it in cDemoClassEx.

Upvotes: 0

mAAdhaTTah
mAAdhaTTah

Reputation: 400

Because cDemoClassEx::getInstance(); is still returning new cDemoClass();. You have to also overwrite the getInstance() method:

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();

Upvotes: 1

Related Questions