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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?