1

Example code 1:

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

Printed:People::status

Example code 2:

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

Printed:Programmer::status

All different in modifier methods private and protected.

Why in first case i get People::status? Why i did not get Programmer::status.

Explain me please, i don't understand this moment.

9
  • 1
    Because People don't have access to Programmer private methods. Commented Jun 1, 2016 at 10:13
  • why? i inherit People class - its mean i have sleep()in Programmer class Commented Jun 1, 2016 at 10:16
  • 1
    Only protected and public methods/variables can an extending class inherit. Commented Jun 1, 2016 at 10:17
  • I talk about status() Commented Jun 1, 2016 at 10:17
  • 1
    Because the method declared under programmer is invalid as it is declared already in parent class as private. Thus in first case parent method gets executed. I recommend you to have a look at this page techflirt.com/tutorials/oop-in-php/classes-and-objects-php.html Commented Jun 1, 2016 at 10:37

1 Answer 1

3

Because in the first case the Sleep method still exists only within People part of the object and cannot access Programmer::status because it is private in Programmer part of the object, but it have another method with that name available and not overwritten, the People::status.

In the second case protected allows Programmer::status to overwrite People::status

Yes, like this it is possible for two methods of the same name to exist in one object, but each one visible only to methods from the same class definition.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.