Kenneth Vogt
Kenneth Vogt

Reputation: 995

How can a PHP class that extends another inherit a private function?

I am trying to extend a PHP class without rewriting the whole thing. Here is an example:

<?
$a = new foo();
print $a->xxx();
$b = new bar();
print $b->xxx();

class foo {
  const something = 10;

  public function xxx() {
    $this->setSomething();
    return $this->something;
  }

  private function setSomething() {
    $this->something = self::something;
  }
}

class bar extends foo {

  public function xxx() {
    $this->setSomething();
    $this->something++;
    return $this->something;
  }

}
?>

However when I run the script I get the following error:

Fatal error: Call to private method foo::setSomething() from context 'bar' in test.php on line 23

It would seem that bar is not inheriting the private function setSomething(). How would I fix this without modifying the foo class?

Upvotes: 9

Views: 26313

Answers (6)

Frank Forte
Frank Forte

Reputation: 2190

Did you try this?

class bar extends foo {

    public function xxx() {
      $this->something = parent::xxx();
      $this->something++;
      return $this->something;
    }
}

Note the parent::xxx(); is public, so it should work... even though it looks like a static call.

Upvotes: 1

Shiplu Mokaddim
Shiplu Mokaddim

Reputation: 57650

No, you can not fix this without modifying the foo class. Because an inherited class can not access parent class's private members. It's a very basic rule.

Declare setSomething() as protected. It'll be solved.

See manual

Upvotes: 15

Christian Mann
Christian Mann

Reputation: 8125

Without modifying the original class, there is no way for the inherited class to directly call private methods of the parent class.

Upvotes: 0

deceze
deceze

Reputation: 522125

bar is inheriting the function alright, but it can't call it. That's the whole point of private methods, only the declaring class can call them.

Upvotes: 7

Shakti Singh
Shakti Singh

Reputation: 86406

Private members are not inheritable, you can not use them in sub class. They are not accessible outside the class.

You must need to make that function as protected or public. Protected members are accessible to that class and for the inherited class. So, your best bet is to make that function Protected.

Upvotes: 8

Related Questions