Class PHP [private vs protected and public]
-
I don't know how to write a title in this case, but what is the question?
Watch the code:
<?php class People { private function status() {return __METHOD__;} public function Sleep(){ echo $this->status().'<br />'; } } class Programmer extends People { private function status() {return __METHOD__;} } $obj = new Programmer(); $obj->Sleep(); ?>
On the way out,
People::status
In this example, we're changing access modes. protected (or public The result will be the same. protected)
<?php class People { protected function status() {return __METHOD__;} public function Sleep(){ echo $this->status().'<br />'; } } class Programmer extends People { protected function status() {return __METHOD__;} } $obj = new Programmer(); $obj->Sleep(); ?>
On the way out,
Programmer::status
How does this mechanism work? I don't understand why. private He doesn't give the same result as he does. protected♪ On the website. php.net I didn't see that.
-
Closed (privatized) methods are available only from within class. When you create a new private method in your heir
Programmer::status()
, you do not redefin the parent method, but you do write a new function with the same name as the parent, but only in another area of visibility. You don't have a different method in your heir.Sleep()
when you challenge:$obj = new Programmer(); $obj->Sleep();
Programmer::Sleep()
♪parent::Sleep()
♪ A in visibilityparent
Methodstatus()
Defined and must return the People:status. I mean, if you'd redesign the method.Programmer::Sleep()
the result would be the same as when changing access retrofits because in this case the code would call the methodSleep()
from its area of visibility.<?php class Programmer extends People { private function status() {return __METHOD__;} public function Sleep(){ echo $this->status().'<br />'; } }
On the way out, we'll get:
Programmer::status
♪Don't declare the closed methods you want to change in your heirs. Specially, there's an access modifier.
protected
such methods will be available to the entire hierarchy of inheritance.