How does a PHP class that extends another inherits a private function?

I am trying to extend the PHP class without rewriting all this. 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 does not inherit the private setSomething () function. How can I fix this without changing the foo class?

+6
source share
6 answers

bar inherits the function in order, but cannot call it. That all points of the methods are private , only the calling class can call them.

+4
source

No , you cannot fix this without changing the foo class. Because the inherited class cannot access the private members of the parent class . This is a very simple oop .

Declare setSomething() as protected . This will be allowed.

See manual

+13
source

Private members are not inherited; you cannot use them in a subclass. They are not available outside the class.

You need to make this feature secure or public. Protected members are available for this class and for the inherited class. So, it’s best to make this feature Protected.

+6
source

Without changing the source class, it is impossible for the inherited class to directly call the private methods of the parent class.

0
source

Have you tried this?

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

Please note: parent :: xxx (); is public, so it should work ... although it looks like a static call.

0
source

Source: https://habr.com/ru/post/912731/


All Articles