MaximPro MaximPro - 6 months ago 19
PHP Question

Class inheritance PHP [private vs protected and public]

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.

Answer

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.