Why are private methods not working with polymorphism?

一曲冷凌霜 提交于 2019-12-11 10:10:13

问题


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"?


回答1:


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.



来源:https://stackoverflow.com/questions/20908078/why-are-private-methods-not-working-with-polymorphism

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!