I may just not have a good enough handle on PHP’s object handling to understand what’s going wrong here, but a snippet of code I have returns results I did not expect and I’m hoping somebody in this crowd can give me some insight into what’s happening. Here is the code:
class Page
{
public function getTitle() {
echo $this->_title();
}
private function _title() {
return "Page Title\n";
}
}
class Title extends Page
{
protected function _title() {
return "Title Title\n";
}
}
$title = new Title();
$title->getTitle();
What I was expecting was that getTitle would be inherited by the Title class and when calling $this->getTitle() would return it’s own method. If you change the _title() method in the parent Page class to protected instead of private, it will do so. But when the parent’s method is private it gets called instead.
Is this expected behavior in object inheritance or some weird issue with PHP? Can anyone explain the (il?)logic of this happening? Much appreciated.
If you copy
Page::getTitle()‘s content toTitle::getTitle()you will get what you intended, which means the$thisinPage::getTitle()always looks in itself for a possible match first and since that is private it does not look any further.As you mentioned, you would have to declare
Page::_title()as protected as well, in order for it to be overridden.