OOP Reference for PHP Guide - Can Someone Explain This?

I saw this in the PHP OOP guide http://www.php.net/manual/en/language.oop5.visibility.php and I can’t understand why the output is not like this: Foo :: testPrivate Foo :: testPublic

class Bar { public function test() { $this->testPrivate(); $this->testPublic(); } public function testPublic() { echo "Bar::testPublic\n"; } private function testPrivate() { echo "Bar::testPrivate\n"; } } class Foo extends Bar { public function testPublic() { echo "Foo::testPublic\n"; } private function testPrivate() { echo "Foo::testPrivate\n"; } } $myFoo = new foo(); $myFoo->test(); // Bar::testPrivate // Foo::testPublic 
+6
source share
3 answers

It's all about the visibility of variables / methods.

You will notice that in the Bar class the testPrivate() method is private . This means that ONLY can access this method itself. No children.

Therefore, when Foo extends Bar , and then asks you to run the test() method, it performs two functions:

  • It overrides the testPublic() method because it is public, and Foo has the right to override it with its own version.
  • It calls test() on Bar (since test() exists only in Bar() ).

testPrivate() not overridden and is part of the class containing test() . Therefore Bar::testPrivate .
testPublic() is redefined and is part of the inheritance class. Therefore, Foo::testPublic .

+11
source

In some cases, it's easy to notice that you need a private method in the Bar class, but you also want a Foo class to access it.

But wait, is it public or private?

The protected modifier is used here.

When a method is private , only the class method can call the method.
When a method is publicly available , everyone can name it as a free party.
When a method is protected , the class itself can call it, and also the one who inherits this method (children) can call it as its own method.

+1
source

I posted the same question a few days ago ... because this behavior was not logical for me. $ this always refers to the current object in which it is used. In my opinion, an example like this should cause an error or warning or something like that. Because in the above example, you actually get access to private members: SSS, WHICH CASE TO BE IMPOSSIBLE!

-1
source

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


All Articles