dongrang2186 2014-01-29 22:05
浏览 24
已采纳

启动按需课程

I am trying to initiate a class on demand.

class MyClass{

    private $modules = array("mod1" => false);

    public function __get($name){
        if(array_key_exists($name, $this->modules) && !$this->modules[$name]){
            $class       = ucfirst($name);
            $this->$name = new $class();
            $this->modules[$name] = true;
        }
    }
}

I then have another class, which then extends the above class. If I do the following the class doesn't get initiated, and I get an error Fatal error: Call to a member function get() on a non-object

class Home extends MyClass{

    public function main(){
        echo $this->mod1->get("cat");
    }

}

But if I do this, the class does get initiated.

class Home extends MyClass{

    public function main(){
        $this->mod1;
        echo $this->mod1->get("cat");
    }

}

Is there any way for me to initiate the class without having to add that extra line?

  • 写回答

1条回答 默认 最新

  • drdawt9210 2014-01-29 22:56
    关注

    Just return it after it's instantiated:

    class MyClass{
    
        private $modules = array("mod1" => false);
    
        public function __get($name){
            if(array_key_exists($name, $this->modules) && !$this->modules[$name]){
                $class       = ucfirst($name);
                $this->$name = new $class();
                $this->modules[$name] = true;
    
                return $this->$name;
            }
        }
    }
    

    Now you can do what you want:

    class Home extends MyClass{
    
        public function main(){
            echo $this->mod1->get("cat");
        }
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥66 换电脑后应用程序报错
  • ¥50 array数据同步问题
  • ¥15 pic16F877a单片机的外部触发中断程序仿真失效
  • ¥15 Matlab插值拟合差分微分规划图论
  • ¥15 keil5 target not created
  • ¥15 C/C++数据与算法请教
  • ¥15 怎么找志同道合的伙伴
  • ¥20 如何让程序ab.eXe自已删除干净硬盘里的本文件自己的ab.eXe文件
  • ¥50 爬虫预算充足,跪巨佬
  • ¥15 滑块验证码拖动问题悬赏