Search code examples
phpobjectinheritancepolymorphismprivate

Why are private methods not working with polymorphism?


Kind of got a problem using inheritance/polymorphism with private methods.

Example:

class cmsPage{

   private function getBlock(){
       $block = new cmsBlock();
       return $block
   }

   function createBlock(){
       $block = $this->getBlock();
       $block->save();
   }
   //... do various things
}


class specialCmsPage extends cmsPage{

   private function getBlock(){
       $block = new specialCmsBlock();
       return $block
   }

}

Naturally I want specialCmsPage to inherit all the methods from cmsPage. The Function getBlock() should make sure all Content Blocks added to specialCmsPage are of type specialCmsBlock and not cmsBlock.

I figured out, that it only works they way I expect it if I remove the "private" from the class methods, but I would prefer to use these, because these methods should not be called from outside a class. Upon using "private" in front of the getBlock() method specialCmsPage always receives a cmsBlock Object.

Is there a way to achieve what I want using "private"?


Solution

  • Perhaps you are looking for protected? private members are visible only to the class in which they are declared. protected members are visible to the class and its descendants.