Get Off My Lawn
Get Off My Lawn

Reputation: 36299

Initiate Class On Demand

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?

Upvotes: 0

Views: 71

Answers (1)

Nathan Bishop
Nathan Bishop

Reputation: 643

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");
    }

}

Upvotes: 1

Related Questions