dsgoj7457 2014-04-29 22:27
浏览 25
已采纳

如何处理对作为另一个对象的私有属性的对象的方法调用?

I have two classes, the Page class and the Template class. A page has a template associated with it, so it stores an object of the Template class as one of it's properties.

Here is my issue. These calsses are used in templating a page. If I want to include the template file, I would call include $Template->view();. However, since this object is a property of the a Page object, I have to call include $Page->template->view();.

This sticks me in the middle of two problems.

  1. If I leave the $Page->template variable public, it could be overwritten at any point with something that isn't a Template object.
  2. Make the $Page->template variable private, and I can no longer access it as I want to by calling $Page->template->method();.

From my point of view, the only option is wrapper methods in the Page class, such as $Page->templateView();.

I am the only one coding this, so option 1 is acceptable, as I will simply no overwrite it, but I wonder if there's a better way. If only there were properties that could be used publicly but not modified publicly.

Is there another choice for handling this type of thing?
Am I over thinking this or missing something?

  • 写回答

2条回答 默认 最新

  • dongshi7433 2014-04-29 22:38
    关注

    You can either:

    a) Make a public accessor method and call it like so:

    class Page
    {
        private $template;
    
        public function template()
        {
            return $this->template();
        }
    }
    
    // call it like this
    $page_object->template()->method();
    

    b) If you don't like using "template()" instead of "template", you can take advantage of magic methods:

    class Page
    {
        private $mTemplate;
    
        public function __get($name)
        {
            if ($name == 'template')
                return $this->mTemplate;
        }
    }
    
    // call it like this
    $page_object->template->method();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题